Can you help me to correct this error?

1 Ansicht (letzte 30 Tage)
Lomi Vo
Lomi Vo am 17 Apr. 2019
Bearbeitet: Jan am 17 Apr. 2019
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 Kommentare
Stephen23
Stephen23 am 17 Apr. 2019
nnz(A~=0)
Lomi Vo
Lomi Vo am 17 Apr. 2019
Thank you so much!

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Jan
Jan am 17 Apr. 2019
Bearbeitet: Jan am 17 Apr. 2019
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)))

Community Treasure Hunt

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

Start Hunting!

Translated by