Pantelis Georgiades
Pantelis Georgiades

Reputation: 13

Variably name histogram in for loop

I'm trying to have a hist function in a for loop because I work with varying amounts of datasets each time and its much faster and easier that having to edit a script each time, but I can't get it right. Can I have some help please? In essence I'm trying to have this in a for loop for variable number of unc{i} datasets and i number of [h{i},x{i}] resulting arrays:

[h1,x1] = hist(unc1,range);
[h2,x2] = hist(unc2,range);
[h3,x3] = hist(unc3,range);
[h4,x4] = hist(unc4,range);

Any help would be greatly appreciated. Thanking you in advance

Upvotes: 1

Views: 57

Answers (2)

Cecilia
Cecilia

Reputation: 4721

You can put each of your input datasets in a cell array, and the output of the histograms in a second cell array.

For example,

unc1 = rand(5,1);
unc2 = rand(5,1);
unc3 = rand(5,1);
unc_cell = {unc1, unc2, unc3};

h_cell = cell(3, 1);
x_cell = cell(3, 1);
for ii = 1:3
    [h{ii} x{ii}] = hist(unc_cell{ii}); 
end

This does require preloading all of the datasets and holding them in memory simultaneously. If this would use too much memory, you can load the datasets in the for loop rather than preloading them.

For example,

h_cell = cell(3, 1);
x_cell = cell(3, 1);
for ii = 1:3
    unc = load(sprintf('data_%d.mat', ii)); %You would replace this with your file name 
    [h{ii} x{ii}] = hist(unc); 
end

Upvotes: 0

Shai
Shai

Reputation: 114786

Desclaimer: the use of eval is dangerous!

Let's say you have n uncs arrays. You can use struct to store them

for ii=1:n
    cmd = sprintf( 's.unc%d = unc%d;', ii, ii );
    eval( cmd );
end

Once you have the uncs is a sttruct, you can simply

for ii=n:-1:1
    [h{ii} x{ii}] = hist( s.(sprintf('unc%d',ii)), range );
end

Notes:
1. Note that I used a backward loop for computing the histograms: this is a nice trick to preallocate h and x, see this thread.
2. It is extremly unwise to use eval, therefore, it might be wiser to create the different uncs arrays as a struct fields to begin with, skipping the first part of this answer.

Upvotes: 2

Related Questions