Reference to non-existent field 'i'.
Show older comments
%% To Create Symbolic symmentric P matrix of Order n*n
n=2;
%n=3;
p_n=(n*(n+1))/2;
P = sym('a', [n n],'real');
P_list = sym('p', [1 p_n],'real');
%logic to generate the Matrix
index=1;
for i=1:n
for j=1:n
if(i<=j)
P(i,j)=P_list(index);
index=index+1;
else
P(i,j)=P(j,i);
end
end
end
P
%% To Create symbolic A in CCF form
%Logic to generate A matrix(In controllable canonical form)
A_list = sym('a', [1 n],'real');
A_list = -A_list;
A=zeros(n-1,n);
for i=1:(n-1)
for j=1:n
if j==i+1
A(i,j)=1;
end
end
end
A=[A ; A_list];
A
%% Solve the symbolic equation using traditional method
% Solving Lyapunov equation symbollicaly
% Uses above generated A and P Matrix
Q_N=-eye(n);
Condition=A'*P + P*A;
Eq=Condition==Q_N;
eqns=[Eq(:)];
vars = P_list;
S = solve(eqns,vars,'Real',true);
%% Display results
%Extracting values from structure S
p1=S.p1
p2=S.p2
p3=S.p3
% p4=S.p4
% p5=S.p5
% p6=S.p6
I am trying to make the above extraction of fields [p1 p2 p3 ....] from structure S to work for any value(integer) of n instead of hardcoding everytime as I doing currently.
I tried with for loop as below but getting the error Reference to non-existent field 'i'.
Is there any way to achieve the task of extraction of fields from Struct (Symbolic Data Type) without hardcoding.
%% Generic way to Display result
%**************THIS SESSION IS CREATING ERROR************************
%n=2 has P_list=[p1,p2,p3]
%n=3 has P_list=[p1,p2,p3,p4,p5,p6]
%n=4 has P_list=[p1,p2,p3,p4,p5,p6,p7,p8,p9,p10]
for i=P_list
i=S.i
end
2 Comments
KSSV
on 20 Jul 2020
Clearly there S do not have i as a field.
KESAVKUMAR A
on 21 Jul 2020
Accepted Answer
More Answers (1)
Read about getfield.
for i=1:length(P_list)
val = getfield(S,P_list{i})
end
3 Comments
KESAVKUMAR A
on 21 Jul 2020
Edited: KESAVKUMAR A
on 21 Jul 2020
KSSV
on 21 Jul 2020
S.a = rand ;
S.b = rand ;
S.c = rand ;
P_list = fieldnames(S) ;
for i = 1:length(P_list)
val = getfield(S,P_list{i})
end
KESAVKUMAR A
on 21 Jul 2020
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!