MATLAB: Another “unable to perform assignment because the indices on the left side are not compatible with the size of the right side” thread.

errorfor loopindexindexingMATLABmatrix

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 3×1, 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

Best Answer

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