Help with the output of my function
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Stephen
il 1 Feb 2014
Commentato: Walter Roberson
il 1 Feb 2014
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 Commenti
Risposta accettata
Walter Roberson
il 1 Feb 2014
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 Commenti
Più risposte (3)
Amit
il 1 Feb 2014
Modificato: Amit
il 1 Feb 2014
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 Commenti
Wayne King
il 1 Feb 2014
Modificato: Wayne King
il 1 Feb 2014
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 Commenti
Stephen
il 1 Feb 2014
2 Commenti
Amit
il 1 Feb 2014
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
il 1 Feb 2014
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.
Vedere anche
Categorie
Scopri di più su Elementary Math in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!