if statements inside a function file and the function called by a for loop
Mostrar comentarios más antiguos
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?
1 comentario
Walter Roberson
el 25 de En. de 2013
Why does your program start with "clear all" ??
Respuestas (3)
Walter Roberson
el 25 de En. de 2013
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
el 25 de En. de 2013
Editada: Roger Stafford
el 25 de En. de 2013
0 votos
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 comentarios
MEXICO
el 25 de En. de 2013
Walter Roberson
el 25 de En. de 2013
Yes, x(n). And assign the result to y(n)
MEXICO
el 25 de En. de 2013
0 votos
1 comentario
Walter Roberson
el 25 de En. de 2013
Please look in the MATLAB documentation for information about logical indexing.
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!