How to use vectors in conditional functions?
이전 댓글 표시
I have a function which accepts four numbers:
function [ force, stiff ] = myfunction( d_a, d_b, v_a, v_b)
After running my function I want to display a surf plot by putting 4 vectors through the function and then plotting.
In the function myfunction, when I introduce conditions (e.g. if, &&, ==) the function does not work. How can I get around this problem?
댓글 수: 4
Gerd
2011년 7월 6일
Hi John,
can you please post some code because otherwise it is hard to tell where the problem is.
Harry MacDowel
2011년 7월 6일
Could you post the codes to further clarify your questions? I do not understand how you write your if condition codes so I cannot tell you what is your problem and how to get around it.
John
2011년 7월 22일
Walter Roberson
2011년 7월 22일
When you have vectors, you need to use | and & instead of || and && .
However, those will generate vectors of logical values. If you want to make decisions based upon the individual logical values, you need to loop or you need to use logical indexing. With a vector of logical values, you can use all() or any() if what you care about is the group behavior of the vector of values.
채택된 답변
추가 답변 (2개)
Daniel Shub
2011년 7월 6일
Without any more information regarding what doesn't work, I am just guessing ...
The == operator with a scalar returns a scalar, with an array it returns an array. You may want to replace
x == y
with
any(x == y)
or
all(x == y)
you may also want to replace && with just & and with |.
John
2011년 7월 20일
댓글 수: 1
Walter Roberson
2011년 7월 20일
John, if "a" is in the range of being greater than 2 and less than 3, then that satisfies a>1 & a<3, so b=1 would be appropriate for that case according to your code. But then you have the "elseif" for a>2 : are you sure that for the range (2,3) you want b=1 and not the b=2 of the elseif ? Otherwise you might as well (for the vector case) use
if a>1 && a<3
b = 1;
elseif a>=3
b = 2;
end
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!