PatStarks
PatStarks

Reputation: 151

How to return answers from Matlab function in form of Symbols

I am trying to return an answer from Matlab in form of a symbolic variable. I created the following code and function to illustrate the error I am receiving:

clc
clear all
syms L real;
% L = 1  % The code works when I uncomment this line
k1 = [ L,  -L;
      -L, 2*L]
k2 = [4*L^2, -L;
      0,      L]
K = GlobalStiffnessMatrix(k1,k2)

The m file GlobalStiffnessMatrix.m is shown below:

function K = GlobalStiffnessMatrix(k12,k23)
    K = zeros(2,2);
    K(1,1) = k12(1,1);
    K(1,2) = k12(1,2);
    K(2,1) = K(1,2);
    K(2,2) = k12(2,2) + k23(1,1);
end

I am receiving the following error:

The following error occurred converting from sym to double: Error using symengine (line 59) DOUBLE cannot convert the input expression into a double array. If the input expression contains a symbolic variable, use VPA.

I have tried to use VPA within the function itself and the simulation code but am still receiving the same error. Of course when I uncomment the line setting L = 1 the function works fine and as expected.

How can I make this function return K as a symbolic variable?

Upvotes: 0

Views: 131

Answers (1)

Wolfie
Wolfie

Reputation: 30047

You're initialising a numerical matrix using

K = zeros(2,2);

Then trying to assign a symbolic variable to each of those numerical elements using

K(1,1) = k12(1,1);

Instead, initialise K as a symbolic 2x2 matrix using sym (see the documentation here).

K = sym('K', [2,2]);

Now each element of K is a symbolic variable and you'll have no issues assigning each one to an existing symbolic variable.

Upvotes: 1

Related Questions