0

I am storing the field variables calculated in a for loop in a vector by appending the values, However I would like to preallocate first for performance. I tried to vectorize this operation but it does not give me what I would like to accomplish. I have put the example of the operation below. How do I do the preallocation in this? For speed.

j=('load raw.mat');
var=fields(j);
val_mat=[];
kk=fieldnames(j);
for i=(length(kk)-Var_no)+1:Var_no+(length(kk)-Var_no)
val_mat=[val_mat j.(var{i})];
end
Johnny
  • 43
  • 6
  • I am confused. This isn't even valid code. Are you just trying to create an array of all field values in a struct? – Suever Nov 23 '16 at 15:25

1 Answers1

3

Based on your code it looks like you are trying to grab all variables stored in raw.mat and concatenate them. To do this, you can replace the loop with struct2cell to convert all field values to a cell array of values and then use cat to concatenate them

data = load('raw.mat');
values = struct2cell(data);
val_mat = cat(2, values{:});

Since we have removed the loop, there is no need to pre-allocate.

I've also taken the liberty to rewrite your code as valid MATLAB code.

Suever
  • 64,497
  • 14
  • 82
  • 101