Reference to non-existent field 'i'.

3 次查看(过去 30 天)
%% 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 个评论
KSSV
KSSV 2020-7-20
Clearly there S do not have i as a field.
KESAVKUMAR A
KESAVKUMAR A 2020-7-21
Thanks for response.
Yes you are right i is not a field in S but when it is assigned to P_list and itterated as below
i got ans as
i=p1
i=p2
i=p3
So tried using S.i inside for loop and got error Reference to non-existent field 'i'.I am confused what does this mean.
for i=P_list
i
end

请先登录,再进行评论。

采纳的回答

Walter Roberson
Walter Roberson 2020-7-21
S.(char(P_list(i)))
  3 个评论
Walter Roberson
Walter Roberson 2020-7-21
After the first iteration you have replaced the function named char with an array named char
In MATLAB it is never possible to compute the name of the output variable in a direct assignment statement. Basically... Don't Do That, it doesn't end well in the long run.

请先登录,再进行评论。

更多回答(1 个)

KSSV
KSSV 2020-7-20
编辑:KSSV 2020-7-20
Read about getfield.
for i=1:length(P_list)
val = getfield(S,P_list{i})
end
  3 个评论
KSSV
KSSV 2020-7-21
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
KESAVKUMAR A 2020-7-21
Thanks.This answer is also acceptable.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Number Theory 的更多信息

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by