how to use an array as the input variable for function

조회 수: 335 (최근 30일)
W. Feng
W. Feng 2022년 7월 20일
편집: Stephen23 2022년 7월 20일
I would like to use an array as the input to call the main function. how to make it?
E.g
function [a b c]=myfunc( x1,x2,x3,x4, ...xn)
a=x1+x2;
b=a;
c=x1*x2*x3...xn;
end
Now I want to use below array as the input to call above function.
Input_data=[¨1 2 3 4 ....n]
feval(myfunc, [1 2 3 4 ... n]) then it's working. But I want to use an array Input to make it rather than list these values.
feval(myfunc, Input_data ) is not working becasue all the values assign to the first variable x1
help help

채택된 답변

Chunru
Chunru 2022년 7월 20일
% Now I want to use below array as the input to call above function.
Input_data=[1 2 3 4 5];
%feval(myfunc, [1 2 3 4 ... n])
[a, b, c] =myfunc(Input_data)
a = 3
b = 3
c = 120
[d, e, f] = myfunc([6 7 3])
d = 13
e = 13
f = 126
%function [a b c]=myfunc( x1,x2,x3,x4, ...xn)
function [a, b, c]=myfunc( x ) % where x is an array
a=x(1)+x(2); % access array elements
b=a;
c=prod(x); % x1*x2*x3...xn;
end

추가 답변 (2개)

W. Feng
W. Feng 2022년 7월 20일
The function file name is M=myfunction.m. and there are 39 inputs.
[ ]=myfunction( a, b,c, ...)
the array X with 39 values as input X=¨[x1,x2,...x39] how to execute the function only use myfunction, and X.
could we do it only use M and X to make it
feval(M(1:end-2), X)
  댓글 수: 2
Chunru
Chunru 2022년 7월 20일
Give a concreate example.
W. Feng
W. Feng 2022년 7월 20일
[M_function, path1, index1]=uigetfile('*.m')
%then select the main function myfunc.m as below m.file
function [y1,y2]=myfunc (x1, x2, x3, x4,x5,x6,x7)
y1=x1+x2+x3+x4+x5+x6+x7;
y2=y1*y1;
%M_function='myfunc.m', the input was stored with
%assume Input=[1,2,3,4,5,6,7] array Input is got from other file.
%How to calculate only with Input, and M_function
%if we use
feval(M_function(1:end-2),1, 2, 3,4, 5 ,6 ,7)
% the calculation is succssful, but I just want to use such synax to use aviable Input instead of using the real value.

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


Stephen23
Stephen23 2022년 7월 20일
편집: Stephen23 2022년 7월 20일
You can use a comma-separated list:
For example:
Input_data = [1,2,3,4];
C = num2cell(Input_data);
[A,B,C] = myfunc(C{:})
A = 3
B = 3
C = 24
function [a b c]=myfunc( x1,x2,x3,x4)
a=x1+x2;
b=a;
c=x1*x2*x3*x4;
end
"The function file name is M=myfunction.m. and there are 39 inputs."
39 positional input arguments is excessive. Most likely you should rewrite the function to accept vector/array inputs, rather than lots and lots of separately-named input arguments. Most likely that would make your code simpler and more efficient, e.g. using PROD rather than repeatedly calling *, just as Chunru showed you.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by