How can I assign an empty value to a variable without getting the error "Unable to perform assignment because the left and right sides have a different number of elements."

20 ビュー (過去 30 日間)
Waseem AL Aqqad
Waseem AL Aqqad 2021 年 12 月 10 日
コメント済み: Waseem AL Aqqad 2021 年 12 月 10 日
MATLAB treats empty values as an empty vector. So, how can I avoid the afforementioned error in this case:
f = zeros(1,50);
for kk = 1: 50
[~, maxidx] = max(Mavg(:,:,kk));
f(kk) = find((Mavg(:,:,kk) <= ratio * N) & (maxidx <= 1:length(Mavg(:,:,kk))), 1 );
if isempty(f(kk))
f(kk) = 51;
end
end
  1 件のコメント
Waseem AL Aqqad
Waseem AL Aqqad 2021 年 12 月 10 日
At some kk values, find() returns an empty vector. So how can I assign a value of 51 to f when find() returns an empty value.
Thanks!

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

採用された回答

Voss
Voss 2021 年 12 月 10 日
編集済み: Voss 2021 年 12 月 10 日
find requires at least one input argument, so I would expect the code as posted to generate an error on the line where find() is called.
find might return an empty array or a scalar or a non-scalar array, so you cannot necessarily assign the result of find to a single element of an array, like you have here: f(kk) = find(); even if the argument(s) to find were valid. (But you can do this assignment if you know find will return a scalar in this particular case.) This assignment operation is the source of the error.
One more thing: isempty(f(kk)) will always return false because f(kk) is always a scalar (because kk is a scalar).
I think you need to assign the result of find to a temporary variable, which you can then check whether or not it's empty, like this:
f = zeros(1,50);
for kk = 1: 50
[~, maxidx] = max(Mavg(:,:,kk));
temp = find(maxidx > 10,1); % use the condition you need here, I just made one up.
if isempty(temp)
f(kk) = 51;
else
f(kk) = temp;
end
end
where the second input argument to find, in this case 1, tells find how many results to return at most, so in this case the result of find is either empty or a scalar value, which is assigned to temp.

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2021 年 12 月 10 日
You can't do that.
N = 50;
f = zeros(1,N);
for kk = 1: N
[~, maxidx] = max(Mavg(:,:,kk));
fkk = find(SOMETHING_NOT_CLEAR_WHAT);
if isempty(fkk)
fkk = N+1;
end
f(kk) = fkk;
end

Community Treasure Hunt

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

Start Hunting!

Translated by