필터 지우기
필터 지우기

How do I sort data by appending a value to an array that may or may not exist?

조회 수: 7 (최근 30일)
Matt Brown
Matt Brown 2018년 1월 26일
답변: Walter Roberson 2018년 1월 26일
I have a large data set that I need to sort into several categories. I have attempted to use the exist command and some if/else statements to determine if it already exists. If it does not, then the variable is created and stored. If it does exist, the value is appended onto the end of the existing array... You will have to forgive the trivialness of the example, it would have been too complicated to share my actual code on this. However, this example does illustrate the issue.
input={'A','A','B','B';5,6,7,8;50,60,70,80;500,600,700,800};
[m,n]=size(input)
for j=1:n
if strcmp(input{1,j},'A')==1
if exist('data.A.row2')==0
data.A.row2=input{2,j};
else
data.A.row2(end+1)=input{2,j};
end
if exist('data.A.row3')==0
data.A.row3=input{3,j};
else
data.A.row3(end+1)=input{3,j};
end
if exist('data.A.row4')==0
data.A.row4=input{4,j};
else
data.A.row4(end+1)=input{4,j};
end
elseif strcmp(input{1,j},'B')==1
if exist('data.B.row2')==0
data.B.row2=input{2,j};
else
data.B.row2(end+1)=input{2,j};
end
if exist('data.B.row3')==0
data.B.row3=input{3,j};
else
data.B.row3(end+1)=input{3,j};
end
if exist('data.B.row4')==0
data.B.row4=input{4,j};
else
data.B.row4(end+1)=input{4,j};
end
end
end
**
This is confusing to me because if I simply enter the following commands into the command line it will append values as I expected. I know it is something stupid on my end, I am just not sure what it is.
data.A.row2=5;
data.A.row2(end+1)=6;
data.A.row3=50;
data.A.row3(end+1)=60;
data.A.row4=500;
data.A.row4(end+1)=600;
data.B.row2=7
data.B.row2(end+1)=8
data.B.row3=70
data.B.row3(end+1)=80
data.B.row4=700
data.B.row4(end+1)=800

답변 (1개)

Walter Roberson
Walter Roberson 2018년 1월 26일
exist() applied to a structure reference returns 0. If you want to know whether a field exists use isfield:
if isfield(data.B, 'row4')

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by