Another "unable to perform assignment because the indices on the left side are not compatible with the size of the right side" thread.
1 view (last 30 days)
Show older comments
CuriousMerchant
on 9 Nov 2019
Commented: CuriousMerchant
on 10 Nov 2019
I couldn't find a solution from earlier threads that was applicable to this particular scenario. Apologies if the solution is obvious.
The following is embedded within two for-loops using variables 'k' and 'c'. The line simply outputs a column vector via some structs I made earlier.
sV = [bodies(k).p - bodies(c).p]'
That works, but I want to produce a 3xN matrix out of the column vectors generated by the for-loops. I thought this would be as simple as changing it to:
sV(k, c) = [bodies(k).p - bodies(c).p]'
But alas, I'm met with the ol' "unable to perform assignment because the indices on the left side are not compatible with the size of the right side."
I'm not sure why the second line doesn't work when the first one does. Surely I'm just specifying that, for each combination of k and c, I want to store these vectors instead of overwriting sV? (Aside: the vectors are all 3x1, so cell arrays shouldn't be necessary).
I hope that's not too cryptic. I would upload the full code but it's large. Very large. Hopefully someone with experience can see what I'm doing wrong!
Many thanks in advance,
- Sam
0 Comments
Accepted Answer
Thiago Henrique Gomes Lobato
on 10 Nov 2019
The problem is only about the indexing. When you do something like sV(k, c), you're actually getting a matrix with all possible permutation betwenn k and c. For you to get only the single combinations you need to convert it to linear indexing, as example the function sub2ind . The following code illustrate in a simplified problem your issue
p = [1:6]';
k = [1:3]';
c = [4:6]';
sV = zeros(6);
% Will not work, since sV(k,c) is a matrix. This is the error that you're getting
%sV(k,c) = [p(k)-p(c)]'
% Will work, since now you get only three index which are the combination
% of both k and c in ther respectively order
ind = sub2ind(size(sV),k,c)
sV(ind) = [p(k)-p(c)]'
sV =
0 0 0 -3 0 0
0 0 0 0 -3 0
0 0 0 0 0 -3
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
More Answers (0)
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!