Assigning or replacing elements of another array into an array based on indices

2 ビュー (過去 30 日間)
Ali Tawfik
Ali Tawfik 2020 年 6 月 3 日
コメント済み: Ali Tawfik 2020 年 6 月 3 日
Hi,
I am trying to replace or assign elements into another array based on indices, I did it but only with only element, I can NOT replace or assign multiple elements
I am using index functions inclduing find but with multiple elements I can NOT.
clear all;
clc;
b = [0 0 45 -45 -45 45 90 90];
t_90_c=find(b==90);
t_0_c=find(b==0);
t_45_c=find(ismember(b,[45 -45]));
b_new=b;
b_new(t_90_c)=8;
%b_new(t_90_c,t_0_c,t_45_c) = [8 9 2] % If I use this line I got an error of subscripted assignment dimension mismatch..
I want the b_new = [ 9 9 2 2 2 2 8 8]

回答 (1 件)

Peter O
Peter O 2020 年 6 月 3 日
Ali,
I suggest you use logical indexing for this instead of FIND. It's faster and a little cleaner.
Hope this helps!
b = [0 0 45 -45 -45 45 90 90];
% Assign each from a test condition.
% You can assign a scalar to multiple values at once.
b_new=b;
b_new(b_new==90) = 8;
b_new(b_new==0) = 9;
b_new(abs(b_new)==45) = 2; % May have unexpected effects on complex qtys. Fine for real-valued.
b_new(b_new == 45 | b_new == -45) = 2; % This uses a compound OR operator to evaluate both +/-45 cases, or if you have two separate cases you want to match.
  1 件のコメント
Ali Tawfik
Ali Tawfik 2020 年 6 月 3 日
Thank you very much, I though I have to assign in one line multiple values,
I totally forgot that b_new is stored so the last b_new will be the result,
Thanks

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

カテゴリ

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