Convert contents of array into index

5 ビュー (過去 30 日間)
Kash022
Kash022 2016 年 11 月 15 日
コメント済み: Alexandra Harkai 2016 年 11 月 15 日
Hello,
I have an array. 1x3127 double which contains the indexes of another array. I want to use those index values to index another array and make those points =0
So for example,
col = [21 34 56 78 54 99];
l(col) = 0; % where l is another array for which I want l(21),l(34),l(56) = 0 etc.
I tried using the following code snippet but it does not work.
col = find(l<0);
for ii = 1:length(col)
a= cell2mat(ii);
l(a) = 0;
end
Please help! Thanks!

採用された回答

Alexandra Harkai
Alexandra Harkai 2016 年 11 月 15 日
Your first code should work.
l = ones(1, 10000); % make sure this is bigger than the largest index col will specify
col = [21 34 56 78 54 99];
l(col) = 0; % this makes the 21st, 34th, 56th, etc. elements 0
  1 件のコメント
Alexandra Harkai
Alexandra Harkai 2016 年 11 月 15 日
Your second code does not work because col is not used anywhere.
col = find(l<0); % this is a 0-1 vector, 1 indicating where l has a negative element
for ii = 1:length(col) % length of col is the number of negative elements in l
a = cell2mat(ii); % this doesn't use col at all
l(a) = 0; % so this puts the 0s in the wrong places
end
This essentially counts how many negative elements are there in vector l (let's say n), then changes the first n elements of l to 0.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by