- Alternatives to the eval Function: https://www.mathworks.com/help/matlab/matlab_prog/string-evaluation.html
- str2func: https://www.mathworks.com/help/matlab/ref/str2func.html
- replace (MATLAB): https://www.mathworks.com/help/matlab/ref/replace.html
How to replace the sdpvar vector x with meshgrid variables to plot it? (YALMIP)
10 次查看(过去 30 天)
显示 更早的评论
I have polynomial f of min degree 2, max degree 6 with variables x1 and x2, which are defined in Matlab by:
x = sdpvar(2,1)
According to this comment, I set the following lines to prepare the polynomial for meshing in order to plot it:
f = f{1};
f = replace(f,'*','.*'); %replace to dot product
f = replace(f,'^','.^'); %replace to dot product
f = eval(['@(x)' f]) %function handle @(x,y)
[X1,X2] = meshgrid(-1:0.01:1,-1:0.01:1); %create meshgrid
f2 = f([X1;X2]); %define f2 as f with x(1)=X1 and x(2)=X2
mesh(X1,X2,f2); %plot f2 in X1 and X2
However I get an error because f2 becomes a scalar, instead of a matrix with all the possible solutions along X1 and X2. Therefore, I cannot plot it with mesh. I tried to follow the steps as given in this answer (link), but although both cases are with two variables, I cannot grasp it.
0 个评论
回答(1 个)
Saarthak Gupta
2023-12-24
Hi,
Looks like you are trying to plot a “sdpvar” expression (YALMIP) over a given domain.
Your code does not correctly parametrize and convert the “sdpvar” expression to a function handle. Based on the given example, "p" represents a bi-variate polynomial in variables “x” and “y”, with a degree of 4. After completing the sum-of-squares decomposition and performing the required adjustments, the function handle is expected to accept two arguments – “x” and “y”. However, the error arises because you have provided only x as the input.
Refer to the following code:
sdpvar x y
[p,c] = polynomial([x y],4); % generate a parameterized polynomial
% solve sum-of-squares decomposition problem using constraints:
% 1. sum-of-squares constraint defined by sos(p)
% 2. p(pi,2) = 3
solvesos([sos(p), replace(p,[x y],[pi 2]) == 3],[],[],c);
% display evaluated polynomial in symbolic MATLAB form.
f = sdisplay(replace(p,c,value(c)));
f = f{1};
f = replace(f,'^','.^'); % element-wise exponentiation
f = replace(f,'*','.*'); % element-wise multiplication
f = str2func(['@(x,y)' f]); % convert function string to function handle
[X,Y] = meshgrid(-1:0.01:1,-1:0.01:1);
F = f(X,Y);
mesh(X,Y,F);
Also, it is not recommended to use “eval” for security and performance considerations. Consider using “str2func” instead.
Refer to the following MATLAB documentation for further reference:
Hope this helps!
Best regards,
Saarthak
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Symbolic Math Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!