Operate by logical arrays element by element (error: Unable to perform assignment because the left and right sides have a different number of elements.)

1 ビュー (過去 30 日間)
FFT
FFT 2021 年 10 月 25 日
コメント済み: FFT 2021 年 10 月 25 日
Hi:
I have a problem using logical arrays. I'd like to use the array for matrix element operation, for example:
a=[1, nan];
b=[8, 9];
I want to replace all nan elements in matrix a and replace it with b. For this example, I want output is [1, 9].
I've tried the followings:
TF= isnan(a); %gives a logical array [0, 1]
a(TF)=b;
or
a(isnan(a))=b;
Both give the error message "Unable to perform assignment because the left and right sides have a different number of elements."
if isnan(a)
a=b;
end
No error message, but all elements in matrix a won't change.
I wonder if there are any ways to do it avoid using for loops (works, but slower)
for i=1:2
if isnan(a(i))
a(i)=b(i);
end
end
Thanks.

採用された回答

Stephen
Stephen 2021 年 10 月 25 日
a = [1,nan];
b = [8,9];
x = isnan(a);
a(x) = b(x)
a = 1×2
1 9

その他の回答 (0 件)

Community Treasure Hunt

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

Start Hunting!

Translated by