필터 지우기
필터 지우기

How to use arrays and functions from a script as input in a matlab function?

조회 수: 2 (최근 30일)
I'm trying to create a function on a script called code1.m, here it's a cosine:
A = 1;
f=input('frequency=')
Ts=0.01;
t = 0:Ts:1;
y = A*cos(2*pi*f *t);
plot(t,y);
ylabel('Amplitude')
xlabel('Time')
Then, use (y, Ts, t) from code1 as inputs in a matlab function, called code2.m file that begins with this code:
function [s1] = serief(y,Ts,t)
close all
Nter=input('Nter=number of terms=')
nter=1:Nter;
N=length(y);
n=0:1:N-1;
figure(1)
plot(n*Ts,y,'.')
And i don't know how to use the inputs in code1.m as the inputs in code2.m
Any insight on how I could do this? I need to do it this way, as later on I have to call the sum of cosines, triangular waves and others (each one a different script) into code2.m, and some of those can't be called through command line, so it has to be read from the script
I tried running code2.m on the command window, and it gives this error:
Error using code2 (line 5)
Not enough input arguments.
Then i tried calling it at the end of code1.m
ylabel('Amplitude')
xlabel('Time')
code2
It runs as follows, and gives this error:
>> code1
frequency=3
f =
3
Nter=number of terms=5
Nter =
5
Error using code2 (line 5)
Not enough input arguments.
Error in code1 (line 11)
code2
If I try to call the function by its name inside the script, it runs as follows
ylabel('Amplitude')
xlabel('Time')
serief(y,Ts,f)
>> code1
frequency=3
f =
3
Undefined function or variable 'serief'.
Error in code1 (line 11)
serief(y,Ts,f)
Same thing if I call it this way:
ylabel('Amplitude')
xlabel('Time')
[s1]=serief(y,Ts,f)

채택된 답변

Walter Roberson
Walter Roberson 2023년 10월 22일
편집: Walter Roberson 2023년 10월 22일
[s1]=code2(y,Ts,f)
That is, you must invoke a function file by the name of the file that stores the function. The function line does not need to match the name of the function.
This only applies to files whose first executable word is function and only applies to the first function in the file -- for all other function calls, the name you use to invoke it must match the name on the function line.
By the way: you will get an error because your function does not assign a value to s1
  댓글 수: 1
David
David 2023년 10월 22일
Thanks for the answer, I ended up coming to that result just now. By testing different ways, I found out that by first running code1.m and then typing code2(y,Ts,t) on the command window, the data of y, Ts and t is still stored on matlab so code2 runs correctly, which I believe is what you're trying to tell me here.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2015a

Community Treasure Hunt

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

Start Hunting!

Translated by