how to change for loop

2 ビュー (過去 30 日間)
etudiant_is
etudiant_is 2016 年 5 月 16 日
回答済み: Jan 2016 年 5 月 16 日
I have
A=[1 ;2; 2; 3; 1]
and
B=[4; 1; 5; 2 ;3]
then I want to have
C=zeros(size(B),1);
for i =1:size(B,1)
C(A(i))=B(i);
end
A, B and C are the same size and A contains the indices but not in order. Without a loop, we can do C(A)=B.
Now if I want to have (C is initialized properly at start )
C=zeros(3,5)
for i =1:size(B,1)
C(A(i),B(i))=5; %or any other value
end
C(A,B)=5 does not give the expected result. Is the principle not the same?

採用された回答

Jan
Jan 2016 年 5 月 16 日
In C(A,B) the indices defined a block, not the linear index. See:
A = zeros(4, 4);
A(2:3, 2:3) = 1;
This does not insert the ones on the center diagonal elements only, but the indices define all 4 elements in teh center.
To get the same result as for the loop, use:
index = sub2ind(size(C), A, B)
C(index) = 1

その他の回答 (1 件)

Roger Stafford
Roger Stafford 2016 年 5 月 16 日
The assignment C(A) = B will work but first you must set up C as a five-element column vector. It does matter what it initially contains:
C = B; % It could also be C = zeros(5,1);
C(A) = B;
  1 件のコメント
etudiant_is
etudiant_is 2016 年 5 月 16 日
Ok, I wanted to confirm this first. I edited my question according to my real problem.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by