if statements inside a function file and the function called by a for loop

조회 수: 3 (최근 30일)
MEXICO
MEXICO 2013년 1월 24일
hi every body im new in matlab and i have this script
clear all
format long
k=100;
dx=1;
x=zeros(k,1);
y=zeros(k,1);
x(1)=1;
for n=2:k;
x(n)=x(n-1)+dx;
[ y ] = test( x );
end
tb=[x(1:k) y(1:k)]
and this function file
function [ y ] = test( x )
if x<25
y=x*2;
elseif x>25
y=x*10;
else
y=x*1000;
end
when i run it just the
else
y=x*1000;
end
part is evaluated, and i want all the x(n) be evaluated in the correct if.
what im doing wrong?

답변 (3개)

Walter Roberson
Walter Roberson 2013년 1월 25일
An evaluated expression is true when the result is nonempty and contains all nonzero elements (logical or real numeric). Otherwise, the expression is false.
What are you testing? x<25.
How big is x?
Does x<25 result in all non-zero elements?

Roger Stafford
Roger Stafford 2013년 1월 25일
편집: Roger Stafford 2013년 1월 25일
When you write "y=test(x)" rather than "y=test(x(n))" or "y=test(x(n+!))", you are passing 'test' an x vector with 100 elements in it and the resulting y will also have 100 elements. At the 'if' and 'elseif' points in 'test' each would always require that the given condition hold for all hundred cases of x and that is never true. Hence only the 'else' part is ever executed. Look up the documentation on 'if' and 'elseif'.
  댓글 수: 2
MEXICO
MEXICO 2013년 1월 25일
ok, im trying to understand (sorry, its cuz my english :S), you are saying that in each if else and else if point the vector x that is 100 is evaluated, so the last statement "else" that is bigger than 25 is always evaluated because x is equal to 100?. so, i have to write "y=test(x(n)) instead of y=test(x). and in the function file i have to use x(n) too?
thanks for the help and your time =)
Walter Roberson
Walter Roberson 2013년 1월 25일
Yes, x(n). And assign the result to y(n)

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


MEXICO
MEXICO 2013년 1월 25일
thanks for the answers, this is just a test of a complex function , but my problem is in the if statements. x is a vector 1:k (k=100) with initial condition x(1)=1, and the function test is composed by a 3 equation where the x's lower than 25 are evaluated in the first if, bigger than 25 in the second and else's in the thirth, the results of the iterations at each case (if's) are listed in tb=[x(1:k) y(1:k)]. but when i run it, just the last else are where the x's are evaluated. so, what i want is n numbers of values of x's be evaluated in the function test where exist 3 equatios for 3 diferent cases of magnitude of x's. =)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by