A MATLAB function with mixed scalar and vector as inputs fail
4 views (last 30 days)
Mohammad Shojaei Arani on 7 Sep 2022
I have a question which I explain by a simple example first. Consider the matlab function
H=@(x,x0,par1,par2)[x+par1 x.^2+par2;1-x.^2-par2 x.^3+par1];
where here x and x0 are vectors but par1 and par2 are scalars. So, H should give us matrices as output (if x and x0 are also
scalars then such matrices are square, otherwise we get non-square matrices). Any of the combinations H([1; 2],[3; 4],1,2), H([1; 2],[3 4],1,2)
H([1 2],[3; 4],1,2) and H([1 2],[3 4],1,2) works and MATLAB does not through any error message.
Now, consider the attached matlab function H_LL(x,x0,par1,par2,par3,par4,par5) which is just longer and has 5 parameters, instead of 2. Unfortunately, this only works if x and x0 are only scalars (and I do not know why!!!)
It would be great if you have an idea what's wrong here?
Walter Roberson on 7 Sep 2022
h_LL = reshape([t3.*t8.*t13.^2.*(-1.0./1.0e+2),t36,t26,t25,t31,t36,par1.^2.*t5.*t7.^2.*t8.*(-1.0./1.0e+2)-par1.*t3.*t6.^3.*t8.*t27.*2.0,t21,t23,t30,t26,t21,t5.*t8.*t15.*(-1.0./1.0e+2),t37,t32,t25,t23,t37,par3.^2.*t2.*t5.*t8.*t15.^2.*(-1.0./2.5e+1)+par3.*t3.*t8.*t15.*t27.*2.0-par3.*t2.*t3.*t8.*t16.*t27.*8.0,t35,t31,t30,t32,t35,t8-t8.^2.*t27.^2.*3.0e+2],[5,5]);
You have 25 components in the , each the same size as your x input. You ask to reshape() that to a 5 x 5 matrix. If x is scalar, that works out fine, a 1 x 25 reshaped to 5 x 5 fits perfectly. But if x were (for example) length 2, you would have a 1 x (25*2) array being reshaped to 5 x 5, and you cannot reshape 50 elements into 25 spaces.
You could edit the code to reshape the input x into the third dimension,
x = reshape(x, 1, 1, );
and then in the assignment to h_LL you could change the reshape from [5,5] to 5, 5,  . This would give you a 5 x 5 x numel(x) result... at the expense of having to manually edit the code.
You cannot convince the Symbolic Toolbox matlabFunction() to itself properly vectorize a function that returns an array (or a function that uses piecewise() or some other functions such as int()) .