Can you help me to correct this error?
1 view (last 30 days)
Show older comments
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 Comments
Answers (1)
Jan
on 17 Apr 2019
Edited: Jan
on 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)))
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!