Conditional Statements for specific elements in Arrays and Matrixes

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

Conditional Statements for specific elements in Arrays and Matrixes

Edward Song
This post has NOT been accepted by the mailing list yet.
This post was updated on .
I'm trying to figure out how to manipulate conditional statements for specific elements in a vector or matrix.

For example, suppose I have a 2x2 matrix M=[2, 9; 5, 1].

I want to test whether each element is greater than four

This won't work:

if (M<=4)
    P=4
    else
        P=5*M
        endif

That won't work because this results in every element of the Matrix being multiplied by 5
or M=[10,45; 25, 5] where I want M=[4,45; 25, 4]

Thus, I could write

if (M(2,1)<=4)
        P=4
        else
            P=5*M(2,1)
            endif

The output is P = 25 which is correct for the one element.

But using this method, I have to write out four if-then-else statements to test each element. For the project I am working with, I potentially have a 6x40 matrix. How would I test each element without having to write out the If-Then-Else statement 240 times?
Reply | Threaded
Open this post in threaded view
|

Re: Conditional Statements for specific elements in Arrays and Matrixes

JokerOne
I am not exactly sure, if this is what you are looking for, but the "find" function might help you

[row_result,col_result] = find(M > 5)

see "help find" for details.
Reply | Threaded
Open this post in threaded view
|

Re: Conditional Statements for specific elements in Arrays and Matrixes

JokerOne
Or, to be more precise, is this, what you are looking for:?
>>> M=[2, 9; 5, 1]
M =

   2   9
   5   1

>>> M_tmp = M.*5
M_tmp =

   10   45
   25    5

>>> [a] = find(M <= 4)
a =

   1
   4

>>> M_tmp(a) = 4
M_tmp =

    4   45
   25    4

>>> M = M_tmp
M =

    4   45
   25    4

>>>
Reply | Threaded
Open this post in threaded view
|

Re: Conditional Statements for specific elements in Arrays and Matrixes

Edward Song
JokerOne, thanks for the reply, and sorry for my belated reply. It looks like your procedure did the job.