Another "unable to perform assignment because the indices on the left side are not compatible with the size of the right side" thread.
조회 수: 2 (최근 30일)
이전 댓글 표시
CuriousMerchant
2019년 11월 9일
댓글: CuriousMerchant
2019년 11월 10일
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
채택된 답변
Thiago Henrique Gomes Lobato
2019년 11월 10일
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!