Hello, I have an array X and another array Y which has some of the indices in array X. I need a new array which will have the X value in the corresponding Y element(index location in X) and zero otherwise. can anybody help me? this is what I tried but it's not working. I'm only getting one value.
X=[11 22 51 28 93 11 124 153 165 176 17 18 19 20];
iY=[1 3 5 9];
for m=1:length(X)
for n=1:length(iY)
if m~=iY(n)
combined_matrix(m)=0;
elseif m==iY(n)
combined_matrix(m)=X(iY(n));
end
end
end

 採用された回答

Birdman
Birdman 2017 年 12 月 25 日
編集済み: Birdman 2017 年 12 月 25 日

0 投票

Do you mean this?
X(~ismember(1:numel(X),iY))=0

3 件のコメント

SSG_newbiecoder
SSG_newbiecoder 2017 年 12 月 26 日
編集済み: SSG_newbiecoder 2017 年 12 月 26 日
if I assign combined_matrix as a zero array with size same as that of X before the for loop, I'll get it. Sorry for asking such a silly doubt
X=[11 22 51 28 93 11 124 153 165 176 17 18 19 20];
iY=[1 3 5 9];
combined_matrix=zeros(size(X));
for m=1:length(X)
for n=1:length(iY)
if m==iY(n)
combined_matrix(m)=X(iY(n));
end
end
end
Birdman
Birdman 2017 年 12 月 26 日
編集済み: Birdman 2017 年 12 月 26 日
Yes but you should avoid using for loops while you can. My solution is really simple. Of course preallocation is something you should do for that case but for loop is not necessary here.
SSG_newbiecoder
SSG_newbiecoder 2017 年 12 月 26 日
編集済み: SSG_newbiecoder 2017 年 12 月 26 日
@Birdman OK,thank you..

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

質問済み:

2017 年 12 月 25 日

編集済み:

2017 年 12 月 26 日

Community Treasure Hunt

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

Start Hunting!

Translated by