how to use an array as the input variable for function
130 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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
0 Commenti
Risposta accettata
Chunru
il 20 Lug 2022
% 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)
[d, e, f] = myfunc([6 7 3])
%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
0 Commenti
Più risposte (2)
Stephen23
il 20 Lug 2022
Modificato: Stephen23
il 20 Lug 2022
You can use a comma-separated list:
For example:
Input_data = [1,2,3,4];
C = num2cell(Input_data);
[A,B,C] = myfunc(C{:})
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.
0 Commenti
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!