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

답변 (1개)

Stephen23
Stephen23 2020년 10월 2일
편집: Stephen23 2020년 10월 3일
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

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

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2020년 10월 2일

댓글:

2020년 10월 3일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by