Conditional replacement of array values from another array

13 ビュー (過去 30 日間)
Kevin Su
Kevin Su 2020 年 4 月 16 日
コメント済み: Kevin Su 2020 年 4 月 16 日
Hello,
I'm trying to resolve what I thought would be a simple issue. To simplify the problem, I have two matrices A and B,
I want to write a loop that scans for values in A that are 500 and then replace then in order with the values from B. I tried the included code, but it just didn't work out.
Any help would be appreciated!
A = [500; 500; 40; 50; 500];
B = [20; 30; 60]
for n = 1:5
for m = 1:3
if A(n,1) == 500
A(n,1) = B(m,1);
else
A(n,1) = A(n,1);
end
end
end
%Desired result is A = [20; 30; 40; 50; 60]

回答 (1 件)

Tommy
Tommy 2020 年 4 月 16 日
Do you need a loop?
If you know there are exactly as many 500s in A as there are values in B:
A(A==500) = B;
If there may be more values in B:
A(A==500) = B(1:sum(A==500));
If there may be more 500s in A:
A(find(A==500, numel(B))) = B;
If you can't be sure:
A(find(A==500, numel(B))) = B(1:min(numel(B), sum(A==500)));
  1 件のコメント
Kevin Su
Kevin Su 2020 年 4 月 16 日
Thanks for such a quick response!
I did not know how many 500s there were in A; I did manage to find a solution; although I'm unsure whether a while loop would be good practice for this.
m = 1;
len = length(B);
while m <= len
for n = 1:5
if A(n,1) == 500
A(n,1) = B(m,1);
m = m + 1;
else
A(n,1) = A(n,1)
end
end
end

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

カテゴリ

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