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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by