how to return the solution of a vector of variables one time instead of indexing sol.x1, solx2..etc
1 次查看(过去 30 天)
显示 更早的评论
Hi. For a system of linear equations, using solve fun, I want to return the solution for all the variables one time. with this function, I can call each solution by indexing which is not practical when I have many variables.
How could I call/return the solution for all the variables one time instead of indexing each variable individually, please?
I need to use the output solutions (solved variables) in another formula. see last 2 lines in the code where I used the for loop for this purpose.
for a large number of variables does not sound practical to call all the variables using the indexing: sol.f1, sol.f2, ...sol.fn for the solution of (f) vector of variables
Here is the code
k_tt=1; k_bt=-3.4744;k_tb=-3.4744;k_bb=18.5263;vp=0.3;
prompt={'a:','N:'};
title='Input';
answer=inputdlg(prompt,title);
a = str2double(answer{1});
N = str2double(answer{2});gam=zeros(N+1,N+1);delt=zeros(N+1,N+1);
A=zeros(N+1,N+1);B=zeros(N+1,N+1);C=zeros(N,N);D=zeros(N,N);Delta=zeros(N+1,1);Delta(1,1)=1;
for ii=0:N
i2=ii+1;
for jj=0:N
jj2=jj+1;
k=ii+jj;
kk=mod(k,2);
if kk==1
gama=0;
else gama=(4*(ii+1)*(jj+1))/((ii+jj+3)*(ii+jj+1)*(ii-jj+1)*(jj-ii+1));
end
gam(i2,jj2)=gama;
if ii==jj
delta1=1;
else delta1=0;
end
delt(i2,jj2)=delta1;
A(i2,jj2)=0.25*pi*(ii+1)*delta1+k_tt*a*gama;
B(i2,jj2)=k_tb*a*gama;
C(i2,jj2)=k_bt*a*gama;
D(i2,jj2)=((3*(3+vp)*pi)/(4*(1+vp)))*(ii+1)*delta1*+k_bb*a*gama;
end
end
f=sym('f',[N+1 1]);g=sym('g',[N+1 1]);
eqns=[A*f+B*g==(pi/2)*Delta,C*f+D*g==(pi/2)*Delta];
S=solve(eqns);
sol =vpasolve(eqns,[f;g]);
sol2=[S.f1;S.g1]; % this way works but I have to call all the variable indivdully! what if I have 100 variables ..i.e. f1...f100, do I need to use (sol.f1 all the way to sol.100)
% the reason is I need to use the solutions in another formula as below
h_1=0
for x=0:N
h_1=h_1+(1+x)* *f(x,1); %f(x,1) refers to the solved variables f1,f2,f3 ... I do not know how to call them here!
end
0 个评论
采纳的回答
Stephen23
2018-11-12
编辑:Stephen23
2018-11-12
You can dynamically access fieldnames:
For example:
S = vpasolve(...);
for k = 1:100
F = sprintf('f%d',k);
S.(F)
end
S = vpasolve(...);
C = struct2cell(S);
V = [C{:}]
You can also use indexing into C to get specific values. You might also find orderfields and/or fieldnames useful (then you can sort the fields and select from fields that actually exist in the structure).
Read more about comma-separated lists:
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Ordinary Differential Equations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!