0

我想根据条件(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

目标:如果code = 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
4

2 回答 2

1

If 语句未向量化。an 的向量化形式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)));
于 2014-03-11T22:55:43.447 回答
0

这不如矢量化优雅,但在这种情况下可能更清晰。它产生两个结构数组。

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
于 2014-03-11T23:56:01.857 回答