Converting a vector to multiple variables required as input for 'matlabFunction'.
Mostra commenti meno recenti
I am converting symbolic function to a Matlab function using 'matlabFunction'.
For e.g.
syms x y
g=matlabFunction(x+y-1)
Output
g = @(x,y)x+y-1.0
The returned matlab function 'g' accepts individual variables like g(1,1). However, I want to give inputs as a vector, like,
input = [1 1]
g(input)
I get error 'Not enough input arguments.' I want to give input as a single vector because number of input in my actual function vary during run-time. Any idea how to convert a vector to multiple variable at run-time efficiently or any other solution.
Risposta accettata
Più risposte (2)
Brad Carman
il 26 Gen 2018
The matlab documentation fails to mention that it's possible to set this up with matlabFunciton() itself. I've discovered that how you input the 'Vars' argument adjusts how the function is built. Using a vector input of variables for 'Vars' will give you what you want. See the following example:
syms x y
z = x+y;
Without vector input:
matlabFunction(z, 'Vars', {x, y})
function_handle with value:
@(x,y)x+y
With vector input:
matlabFunction(z, 'Vars', {[x, y]})
function_handle with value:
@(in1)in1(:,1)+in1(:,2)
3 Commenti
Juan Jurado
il 5 Mar 2018
Wow! I've been using the ol'"g(input{:})" trick for years until I stumbled onto your answer. Specifying "Vars" as a vector in the matlabFunction function works like a charm!!!
Ti Miller-Jackson
il 21 Ago 2019
Oh my gosh this works so well! You just saved me many hours. God bless you sir!
Graham Rowe
il 7 Nov 2020
This should be the accepted answer. So much more elegant than defining temporary variables that get created and then removed at run time.
Azzi Abdelmalek
il 24 Set 2012
Modificato: Azzi Abdelmalek
il 24 Set 2012
g = @(x,y)x+y-1.0
%g is a function of two inputs x and y, if you want one vector input
g=@(x) x(1)+x(2)-1.0
%then
g([2 3])
=4
1 Commento
Taimoor Saif Talpur
il 24 Set 2012
Categorie
Scopri di più su Conversion in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!