How can I substitute a variable given by a struct?

조회 수: 5 (최근 30일)
Abner Ojeda
Abner Ojeda 2020년 5월 2일
댓글: Abner Ojeda 2020년 5월 3일
Hey, everyone. I'm trying to solve an optimization problem without the Optimization toolbox. I already have the roots from the equation (by "solve"), it gives to me an struct array, with fields x1, x2... xn, my problem is I already have an x1, x2... xn. I've been trying by so many ways but simply I couldn't solve it, I'm looking to asign the value of the fields to the syms variables and then apply "subs". Code below.
Thanks in advance for help. :)
clear; close all; clc;
var= input ('Dimention of domain');
syms x [1 var];
func= input ('Enter the function, i.e [x1+x2+...+xn]: \n');
y=[];
for s=x(1:end)
dp= diff (func, [s]);
y=[y, dp];
end
pc=solve (y);
pucr= fieldnames (pc);
for i= 1:numel(pucr)
vals(i, 1)= getfield(pc,pucr{i});
end
Hf=hessian (func);
Hff= subs (Hf);
  댓글 수: 2
darova
darova 2020년 5월 2일
Try this
for i= 1:numel(pucr)
v = getfield(pc,pucr{i});
v1 = subs(v,oldv, newv);
vals(i, 1) = doulbe(v1);
end
Abner Ojeda
Abner Ojeda 2020년 5월 3일
Thanks for taking your time in answer my question, it doesn't work, but I appreciate your answer.

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2020년 5월 2일
subs(ExpressionToSubstituteInto, pc)
When pc is a struct with field names, then the corresponding variable names will have the appropriate values substituted.
Note: this will not work if any of the field names contain an empty value, even if the corresponding variable is not used in the expression. In particular, if you happened to do
pc = solve(y, 'returnconditions', true)
then pc.parameters would be created even if no parameters were generated, and with pc.parameters being empty, subs() with pc would fail. You can get it working by removing the empty field from the struct.
  댓글 수: 1
Abner Ojeda
Abner Ojeda 2020년 5월 3일
It works, Walter, it works pretty well. Thank you.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by