How to use the diagonal symbol matrix?

I want to use a diagonal symbol matrix in my code, as in the following:
syms a1 a2 a3
a = diag([a1,a2,a3]);
M = matlabFunction(2*a,'vars',{a});
But there's a problem:
Error using sym/matlabFunction>checkVars
Variable names must be valid MATLAB variable names.
Error in sym/matlabFunction (line 158)
vars = checkVars(funvars,opts);

 Accepted Answer

Need to specify the vars explicitly if defined individually
syms a1 a2 a3
A = diag([a1,a2,a3])
A = 
M = matlabFunction(2*A,'Vars',[a1,a2,a3])
M = function_handle with value:
@(a1,a2,a3)reshape([a1.*2.0,0.0,0.0,0.0,a2.*2.0,0.0,0.0,0.0,a3.*2.0],[3,3])
Or more compactly
a = sym('a',[1 3])
a = 
A = diag(a)
A = 
M = matlabFunction(2*A,'vars',a)
M = function_handle with value:
@(a1,a2,a3)reshape([a1.*2.0,0.0,0.0,0.0,a2.*2.0,0.0,0.0,0.0,a3.*2.0],[3,3])

2 Comments

a = sym('a',[1 3])
a = 
A = diag(a)
A = 
M = matlabFunction(2*A,'vars',{a})
M = function_handle with value:
@(in1)reshape([in1(:,1).*2.0,0.0,0.0,0.0,in1(:,2).*2.0,0.0,0.0,0.0,in1(:,3).*2.0],[3,3])
It's working,Thanks!

Sign in to comment.

More Answers (0)

Products

Release

R2023b

Tags

Asked:

on 26 Dec 2024

Commented:

on 26 Dec 2024

Community Treasure Hunt

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

Start Hunting!