1

I have a 2417-by-50 structure array in MATLAB and am trying to find a vectorized way to convert some of the field types:

  1. I have a column of characters that I want to convert into a string type:

    [DataS.Sector] = string([DataS.Sector]);
    

    but its not working. I don't want to use a loop since it take so much time.

  2. Same issue, but converting to numeric values. Right now I'm using a loop that takes a really long time:

    for i = 1:length(DataS)
      for j = 1:numel(Vectorpour)
        DataS(i).(DataSfieldname{k}) = str2double(DataS(i).(DataSfieldname{k}))
      end
    end
    

How can I vectorize each of these approaches?

gnovice
  • 125,304
  • 15
  • 256
  • 359
MC_B
  • 31
  • 4

1 Answers1

1

You can perform both of these conversions across all elements of your structure array by capturing the field values in a cell array, doing the conversion (using string or str2double), converting the result to a cell array using num2cell, then overwriting the original fields using a comma-separated list:

% For part A:
temp = num2cell(string({DataS.Sector}));
[DataS.Sector] = temp{:};

% For part B:
temp = num2cell(str2double({DataS.(DataSfieldname{k})}));
[DataS.(DataSfieldname{k})] = temp{:};
gnovice
  • 125,304
  • 15
  • 256
  • 359