Question

I would like to assign input data to 2 different structs, depending on a condition (Matlab). What is the best way to do this?

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

Goal: If code = 0, assign to struct A. If not, assign to struct B.

Here's what I tried. Just a shot in the dark, really.

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
Was it helpful?

Solution

If statements are not vectorized. The vectorized form of an if uses a vector of booleans.

Something like this should work:

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)));

OTHER TIPS

This is less elegant than vectorizing, but in this case may be clearer. It produces two arrays of structures.

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top