Help with the output of my function
조회 수: 1 (최근 30일)
이전 댓글 표시
Hi, I have written the following function which works fine when I pass it a value such as 2. But when I say something like:
>> i = -2.5:0.1:2.5;
>> p = myfun1(i);
I get there error:
Error in myfun1 (line 3)
if abs(t) <= 1
Output argument "result" (and maybe others) not assigned during call to "/Users/mbxs3/Desktop/VCU/VCU Spring 2014/EGRE 335 - Signals and Systems/MATLAB/myfun1.m>myfun1".
Here is my function code:
function result = myfun1(t)
if abs(t) <= 1
t1 = (2-abs(2*t));
result = t1;
elseif t < -1
t2 = 0;
result = t2;
elseif t > 1
t3 = 1;
result = t3;
end
댓글 수: 0
채택된 답변
Walter Roberson
2014년 2월 1일
You should learn how to use logical indexing.
function result = myfun1(t)
result = zeros(size(t));
idx = abs(t) <= 1;
result(idx) = (2-abs(2*t(idx)));
idx = t < -1;
result(idx) = 0;
idx = t > 1
result(idx) = 1;
댓글 수: 0
추가 답변 (3개)
Amit
2014년 2월 1일
편집: Amit
2014년 2월 1일
This is because when you input t as a vector, unless all of the values in vector satisfy the condition, it will not go through any of the if ... end statements.
When this happens, the value for result does not get declared and thats why you'll get error.
If you tell us, what you're trying to do in this code, maybe people can help you in fixing the issue
댓글 수: 0
Wayne King
2014년 2월 1일
편집: Wayne King
2014년 2월 1일
First don't use i, i the unit imaginary. That can often cause problems.
Next, you are giving it a vector input. What do you actually want to know when you write
abs(t) <=1
Do you want to know if there are ANY elements in the input that are less than 1, or whether ALL elements are?
If so use, any() and all()
if all(abs(t)<=1)
result = (2-abs(2*t));
end
or
if any(abs(t)<=1);
result = (2-abs(2*t));
end
댓글 수: 0
Stephen
2014년 2월 1일
댓글 수: 2
Amit
2014년 2월 1일
You should try Walter's method. That will give you the result.
And using i and j are choices by the user And Wayne's comment was just a reminder to you just in case you dont know.
Walter Roberson
2014년 2월 1일
The code I gave in my answer will output the values you would like.
By default, i and j are both initialized to sqrt(-1), as variables. You can change either or both. However, people tend to confuse "i" used as a loop variable and "i" used as sqrt(-1), so it is usually clearer to avoid using "i" as a variable.
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!