Unable to accept a vector as parameter in user defined function.

I made a function to add a set of 'n' sine terms as per my algorithm.
function inst_amplitude = sincustom(t,[FreqList],[AmpList])
%UNTITLED3 Summary of this function goes here
% Detailed explanation goes here
l_freq=length(FreqList);
l_amp=length(AmpList);
result=0;
if l_freq ~= l_amp
result=0;
else
for i=1:l_amp
result=result+(AmpList[i].*sin(t.*FreqList[i]));
end
end
return result;
end

Answers (1)

A valid function definition requires the name of the input argument/s (no square brackets like you used):
function result = sincustom(t,FreqList,AmpList)
Also note that indexing in MATLAB uses parentheses (not square brackets like you used):
result = result + AmpList(i).*sin(t.*FreqList(i));

3 Comments

Got this error
Error: File: sawtoothcustom.m Line: 14 Column: 8
Invalid expression. Check for missing multiplication operator, missing or unbalanced delimiters, or other syntax error. To
construct matrices, use brackets instead of parentheses.
function inst_amplitude = sincustom(t,FreqList,AmpList)
l_freq=length(FreqList);
l_amp=length(AmpList);
result=0;
if l_freq ~= l_amp
result=0;
else
for i=1:l_amp
result = result + AmpList(i).*(sin(t.*FreqList(i)));
end
end
return result;
end
"Got this error"
Error: File: sawtoothcustom.m Line: 14 Column: 8
The code you posted has only 13 lines in total, and is named sincustom, so the error appears to occur in some code that you have not shown us. I cannot degug code that I cannot see, nor have any idea how it is being called.
Note that this line:
return result;
does not "return" the variable result, it simply returns exits the function at that point (note that the return documentation does not mention anythingn about it accepting an argument, so it is not clear what you expect if you provide it with one). If you want to return the variable named result, then you need to define it as an output argument (currently the output argument inst_amplitude is not defined anywhere), you do not need to use return at all:
function result = sincustom(t,FreqList,AmpList)
% ^^^^^^^ outputs are defined here!
Thanks! Got my mistake. I was trying other functions in hope of getting it running

Sign in to comment.

Categories

Find more on Loops and Conditional Statements 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!