IF argument question I am seriously new to coding.
Show older comments
Ok, Im trying to output c1 for x from 0 to 10. Im looking for it to return c1=0 0 0 0 0 0 0 0 1 2 but it keeps giving me c1=-8 -7 -6 -5 -4 -3 -2 -1 0 1 2
if the function c is less than zero I am trying to tell it to make c1=0, and if c is greater than zero to make c1 whatever c would be.
function beam_displac(x)
L=0:x
c=(L-8)
if c <= 0
c1= 0
else c1=c
end
What am I doing wrong? How might I do this? Thanks
Accepted Answer
More Answers (2)
Walter Roberson
on 9 Feb 2014
0 votes
Your "c" is a vector. When you have "if" with a vector argument, it is considered to be true only if all the vector values are considered true. Any non-zero value is considered true. If your x value that you pass in is less than 8, then none of your c values will be 0 and so the "if" will be considered true. But if your "x" value that you pass in is 8 or higher, then one of your c values is going to end up as 0 and the "if" will be considered false.
You should use a "for" loop, or you should use "logical indexing"
Roger Stafford
on 9 Feb 2014
Edited: Roger Stafford
on 9 Feb 2014
0 votes
The trouble with your code is that 'c' as you have defined it, is a vector with many elements. When you write "if c<=0", the quantity c<=0 is a corresponding logical vector, and the 'if' condition is considered satisfied only if all the elements in the logical vector are true. That is clearly not what you intended. You apparently had in mind that the if-else-end form would be operated element-by-element making as many decisions as there are elements in c. That is not how if-else-end works. It either goes one way or the other way, one time only. Therefore you have to adopt some method which forces matlab to make individual decisions for each element. The relevant 'if' documentation reads: "An evaluated expression is true when the result is nonempty and contains all nonzero elements (logical or real numeric). Otherwise, the expression is false."
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!