Clear Filters
Clear Filters

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)
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

Accepted Answer

Thiago Henrique Gomes Lobato
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
  1 Comment
CuriousMerchant
CuriousMerchant on 10 Nov 2019
Thank you for the help! The above sent me in the right direction. You mentioned using sub2ind which pointed me towards cell2mat, which I didn't know existed (newbie here) and was exactly what I needed.
In the end I created an array (line 1), removed all the empty cells (line 2) and then converted the array to a matrix of column vectors (line 3) via cell2mat.
sV{k,c} = [bodies(k).p - bodies(c).p]'
sV_noZeros = [sV(~cellfun('isempty', sV))]';
sV_mat = cell2mat(sV_noZeros)
Thanks, Thiago!

Sign in to comment.

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!