Can you help me to correct this error?

1 回表示 (過去 30 日間)
Lomi Vo
Lomi Vo 2019 年 4 月 17 日
編集済み: Jan 2019 年 4 月 17 日
Hello guys, I have code here:
clc
clear all
A=[0,0,0;0,0,0;0,0,0;0,0,0;1,5,4;7,6,9;3,2,8];
[m,n]=size(A);
count=0;
while isempty(A)==0
[target, min_idx]=min(A(A~=0));
[rmin,cmin]=ind2sub(size(A),find(A==target));
for c=1:rmin
if A(c,cmin)==target
count=count+1;
A(c,cmin)=0;
end
end
end
disp(count);
And when I run the code, i got this result:
Error using ==
Matrix dim
It has problem in this line
[rmin,cmin]=ind2sub(size(A),find(A==target));
I want to find the minimum number in matrix A and replace it by 0, then count the number of move. The loop will run until matrix A becomes zero.
Please help me to correct it, thank you very much!
  4 件のコメント
Stephen23
Stephen23 2019 年 4 月 17 日
Lomi Vo
Lomi Vo 2019 年 4 月 17 日
Thank you so much!

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

回答 (1 件)

Jan
Jan 2019 年 4 月 17 日
編集済み: Jan 2019 年 4 月 17 日
while isempty(A)==0 will not work, because the matrix A does not change its size. I guess you mean:
while any(A(:) ~= 0)
% Or short: while any(A, 'all')
% Or nnz(A~=0) % as Stephen has suggested
The error occurred, when A does not contain elements, which differ from 0. Then:
[target, min_idx]=min(A(A~=0));
replies an empty target and A==target is not defined.
Use logical indexing inside the loop:
target = min(A(A~=0));
index = (A == target);
A(index) = 0;
count = count + nnz(index);
An easier approach without a loop:
count = numel(unique(A(A~=0)))

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by