Borrar filtros
Borrar filtros

while loop, index out of bounds

2 visualizaciones (últimos 30 días)
nomad nomad
nomad nomad el 7 de Mayo de 2011
I want to sum the matrix elements classified if the sum> 0, remove the max, and the sum <0 delete min, until the sum be equal to zero.
I tried this loop:
matrice=sort(Deltaf,'descend') ;
while sum(matrice)~=0
if sum(matrice)>0
matrice = matrice(2:end, : );
else sum(matrice)<0
matrice = matrice( :,end-1 );
end
end
With this error:
??? Attempted to access matrice(:,0); index must be a positive integer or logical.
Error in ==> test at 105 matrice = matrice( :,end-1 );
[EDITED, Jan, code formatted]

Respuestas (2)

Daniel Shub
Daniel Shub el 7 de Mayo de 2011
You have removed all the elements from your matrix. There is no gaurentee that an arbitraty matrix will sum to 0. Think about [1, 2, 3] or [-3, -1, 2, 4] or [-1, 1+eps].

Teja Muppirala
Teja Muppirala el 7 de Mayo de 2011
If Deltaf is really a vector, not a 2D matrix, then what you are doing will work fine once you take out the unnecessary colons.
As Daniel pointed out, depending on your data, you might end up with an empty matrix. But at least you shouldn't get an error.
matrice=sort(Deltaf,'descend') ;
while sum(matrice)~=0
if sum(matrice)>0
matrice = matrice(2:end);
else
matrice = matrice(1:end-1);
end;
end;
matrice
  2 comentarios
nomad nomad
nomad nomad el 7 de Mayo de 2011
Hello,
To make a loop that stops when the sum of positive and negative elements is zero
But I find myself with an empty matrix....
Where is the problem
Matt Fig
Matt Fig el 7 de Mayo de 2011
The problem has already been shown to you. Stop for a minute and think about what you are doing. There is no guarantee that an arbitrary matrix will have a zero sum by successively removing the largest and smallest element. Instead of asking why your method isn't working over and over, think for a minute. Do an example:
A = [1 2 3 4]
Now use your method on A. You will NEVER get to zero by summing any subset of the elements of A!

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements 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