Question

I want to test a function func(par1,par2,par3) with all combinations of the parameters par1, par2 and par3 and store the output in a .mat file. My code looks like this at the moment:

n1 = 3;
n2 = 1;
n3 = 2;

parList1 = rand(1,n1);    % n1,n2,n3 is just some integer
parList2 = rand(1,n2);    % the lists are edited by hand in the actual script
parList3 = rand(1,n3);

saveFile = matfile('file.mat','Writable',true);
% allocate memory    
saveFile.output = NaN(numel(parList1),numel(parList2),numel(parList3));  

counter1 = 0;
for par1 = parList1
    counter1 = counter1 + 1;
    counter2 = 0;    % reset inner counter
   for par2 = parList2
     counter2 = counter2 + 1;
     counter3 = 0;   % reset inner counter
      for par3 = parList3
         counter3 = counter3 + 1;
         saveFile.output(counter1,counter2,counter3) = sum([par1,par2,par3]);
      end
   end
end

This works except if parList3 has only one item, i.e. if n3 = 1. Then the saveFile.output has singleton dimensions and I get the error

Variable 'output' has 2 dimensions in the file, this does not match the 3 dimensions in the indexing subscripts.

Is there a elegant way to fix this?

Was it helpful?

Solution

The expression in the for statement needs to be a row array, not a column array as in your example. The loops will exit after the first value with your code. Set a breakpoint on the saveFile.output command to see what I mean. With a column array, par1 will not be a scalar as desired, but the whole parList1 column. With a row array, par1 will iterate through each value of parList1 as intended

Another thing is that you need to reset your inner counters (counter2 and counter2) or your second and third dimensions will blow up larger than you expected.

The n3=1 problem is expected behavior because matfile defines the variables with fixed number of dimensions and it will treat saveFile.output as 2D. Once you have fixed those issues, you can solve the n3=1 problem by changing the line,

saveFile.output(counter1,counter2,counter3) = sum([par1,par2,par3]);

to

if n3==1, saveFile.output(counter1,counter2) = sum([par1,par2,par3]);
else saveFile.output(counter1,counter2,counter3) = sum([par1,par2,par3]);
end

OTHER TIPS

By now I realized that actually in matfiles all the singleton dimensions, except for the first two are removed.

In my actual programm I decided to save the data in the file linearly and circumvent matfile's lack of linear indexing capability by using the functions sub2ind and ind2sub.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top