Setting limits using If statements

조회 수: 5 (최근 30일)
JR
JR 2017년 7월 11일
댓글: KSSV 2017년 7월 11일
Consider a random matrix:
A=[1.8 2.6 3.4 4.0 7.2]
[0.5 0.4 0.3 0.2 0.1]
I want to write a code that scans through A and does something if some conditions against parameters P1 and P2 are satisfied. Could somebody help me convert my pseudo code into a MATLAB script.
-----------------------------------------------------------------------------------
Pseudocode
-----------------------------------------------------------------------------------
P1=3.5;
P2=0.39;
for i=1 : (number of rows)
if an element A(i,:) is greater than or equal to P1
store all the elements from A(i,:) that come before P1;
but if an element A(i,:) is less than or equal to P2
store all the elements from A(i,:) that comes before P2;
end if
end for
-----------------------------------------------------------------------------------
Expected Output:
StoredElements = [ 1.8 2.6 3.4 ]
[ 0.5 0.4 ]
-----------------------------------------------------------------------------------

답변 (1개)

KSSV
KSSV 2017년 7월 11일
This is pretty simple...you need not to run a loop. Read about find. http://in.mathworks.com/help/matlab/ref/find.html.
Also you can use the logical indexing. Ex..to get all the values in A which are less then or equal to p1..use
store = A(A(<=p1)
  댓글 수: 2
JR
JR 2017년 7월 11일
Thanks. It works if I write
store = A(A<P1)
but this will give me all the values in A that satiesfies the condition. What I want is to check it per row such that I tried writing my code this way:
store =A(1,:)(A(1,:)<P1)
But what I am getting is an error: Error: ()-indexing must appear last in an index expression.
KSSV
KSSV 2017년 7월 11일
To run that in first row use:
A(1,A(1,:)<=P1)

댓글을 달려면 로그인하십시오.

카테고리

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