If statements with matricies

I am trying to display the matrix positions (Row and column) where the entries are greater than 10 in a given matrix.
I figured a good way to do this is to use the find(x>10) command and if the values are within a range I specify (In this case if find(x>10) >2) then I would subtract two (if the matrix is 2x2) from those two values only. (This would find the row number)
So say find(x>10) yielded the following
ans=
2
3
4
Then that would mean that in position 2,3 and 4 there are values greater than 10 and I would need to subtract 2 from the specific entries in ans. I would do something similar for the columns.
Is this a good way to go about this? Any suggestions?

 Respuesta aceptada

Matt Fig
Matt Fig el 1 de Mzo. de 2011

1 voto

You might want the two output version of FIND. The one output version does not return the row number, but the linear index.
x = magic(6); % Sample data
[I,J] = find(x>10); % I is rows, J is columns.
Now if your goal is only to subtract 2 from the values of x which are greater than 10, and whos row and column position are greater than two (as I read your somewhat confusing post), do this:
idx = I>2 & J>2;
idx = sub2ind(size(x),I(idx),J(idx));
x(idx) = x(idx)-2
Note, if you want to display the positions, you could just use:
x>10 % Shows in command window
spy(x>10) % Shows a graph.

5 comentarios

Matt
Matt el 1 de Mzo. de 2011
I apologize for the confusing post, I was writing it in a hurry.
But I see! The problem is, my professor wants us to do it without the [I,J] command. I recall someone asking about it in class and I did not know what they were talking about until I read your post. How would I go about this without that command?
Paulo Silva
Paulo Silva el 1 de Mzo. de 2011
For matrices, [I,J] = ind2sub(size(A),find(A>5)) returns the same values as [I,J] = find(A>5)
Matt Fig
Matt Fig el 1 de Mzo. de 2011
Well, you do see the SUB2IND command, right? If you look at the help for this function, you will see its cousin IND2SUB.
The only other suggestion would be to do it in a double FOR loop:
for ii = 3:size(x,1)
for jj = 3:size(x,2)
% Do your stuff here.
end
end
Matt
Matt el 1 de Mzo. de 2011
Cool! Thanks a lot!
Jan
Jan el 1 de Mzo. de 2011
@Matt: Does this mean, that you accept the answer? Then enable the "Accepted" flag, please.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Etiquetas

Preguntada:

el 1 de Mzo. de 2011

Community Treasure Hunt

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

Start Hunting!

Translated by