Can you help me to correct this error?

1 visualización (últimos 30 días)
Lomi Vo
Lomi Vo el 17 de Abr. de 2019
Editada: Jan el 17 de Abr. de 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 comentarios
Stephen23
Stephen23 el 17 de Abr. de 2019
Lomi Vo
Lomi Vo el 17 de Abr. de 2019
Thank you so much!

Iniciar sesión para comentar.

Respuestas (1)

Jan
Jan el 17 de Abr. de 2019
Editada: Jan el 17 de Abr. de 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)))

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by