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!