Matlab 使用条件语句分配结构
我想根据条件(Matlab)将输入数据分配给2个不同的结构。最好的方法是什么Matlab 使用条件语句分配结构,matlab,struct,conditional-statements,textscan,Matlab,Struct,Conditional Statements,Textscan,我想根据条件(Matlab)将输入数据分配给2个不同的结构。最好的方法是什么 FILE points.dat % Point ID X Y CODE Station1 2.2 4.5 0 Station2 5.1 6.7 0 Station3 7.3 3.2 1 Station4 2.1 5.0 1 目标:如果代码=0,则分配给结构A。如果不是,则分配给结构B 这是我试过的。只是黑暗中的一枪,真的 fid = fopen
FILE points.dat
% Point ID X Y CODE
Station1 2.2 4.5 0
Station2 5.1 6.7 0
Station3 7.3 3.2 1
Station4 2.1 5.0 1
目标:如果代码=0,则分配给结构A。如果不是,则分配给结构B
这是我试过的。只是黑暗中的一枪,真的
fid = fopen('points.dat');
C = textscan(fid, '%s %f %f %f', 'CommentStyle','%');
fclose(fid);
if (C{4} == 0)
A = struct('id',C{1}, 'x', num2cell(C{2}), 'y', ...
num2cell(C{3}), 'code', num2cell(C{4}));
else
B = struct('id',C{1}, 'x', num2cell(C{2}), 'y', ...
num2cell(C{3}), 'code', num2cell(C{4}));
end
如果语句没有矢量化。
if
的向量化形式使用布尔向量
像这样的方法应该会奏效:
mask = (C{4} == 0);
A = struct('id',C{1}(mask), 'x', num2cell(C{2}(mask)), ...
'y', num2cell(C{3}(mask)), 'code', num2cell(C{4}(mask)));
B = struct('id',C{1}(~mask), 'x', num2cell(C{2}(~mask)), ...
'y', num2cell(C{3}(~mask)), 'code', num2cell(C{4}(~mask)));
这不如矢量化优雅,但在这种情况下可能更清晰。它生成两个结构数组
A=[];
B=[];
for i=1:4
temp.id={C{1}(i)}; %the second set of braces turn it from a cell to a string
temp.x =C{2}(i);
temp.y =C{3}(i);
if C{4}(i)==0
A=[A;temp]; %concatenate
else
B=[B;temp];
end;
end
每个
code
值的多个数据点如何?您希望使用单独的结构,例如x=2.2
和x=5.1
(即结构数组),还是使用x=[2.2,5.1]
(数组结构)?