MATLAB: How can i build a for loop to create histograms for a multiple cell array

cellcell arraysfor loop

i have a multiple array cells (result):
there are 20 cells and each cell contains other 20 cells. I would like to create an histogram of each cell data, so in total 400 histograms. I built this code but if I have ii=1 i have L_nod starting from result{1,1}{1,2}. I want that it starts from result{1,1}{1,1} and increase each time.
for ii = 1:length(result)
figure(ii)
L_nod = result{1,ii}(:,ii+1)
L_nodo1 = cell2mat(L_nod);
[n,x] = hist(L_nodo1,50);
n = n/length(L_nodo1)/diff(x(1:2));
bar(x,n,'hist')
pngFileName = sprintf('hist%d.png',ii);
fullFileName = fullfile(folder, pngFileName);
saveas(gcf,fullFileName);
end
maybe is not clear, if anybody has a new code to suggest to me i'm glad :).
Thanks!

Best Answer

First, don't use 2D indexing for vectors. result{ii} will work whether result is a row or column vector. Your result{1, ii} will only work for a row vector and fail if that untested assumption is broken.
Note that the output of result{ii} (or result{1, ii}) is, as you've stated a 1x20 cell array. Again, it's a vector and you're using 2D indexing on that with index (:, ii+1). Since that cell array has only 1 row, : is equivalent to 1, so your Lnodo1 is:
Lnodo1 = cell2mat(result{1, ii}(1, ii+1));
written a lot more simply as
Lnodo1 = result{ii}{ii+1}; %the use of cell2mat is pointless, {} indexing instead of () indexing yields the same result
So basically, you Lnodo1 is in turn result{1}{2}, result{2}{3}, ..., result{20}{21}. That last one will cause an index exceeds matrix dimension error as well. Certainly it doesn't do what you want but I'm not sure why you didn't spot that.
Since you want to interate over the cells of the outer array and the cells of the inner array, you need a double for loop
for outer = 1:numel(result) %prefer numel to length, it's safer
for inner = 1:numeL(result{outer})
L_nodo1 = result{outer}{inner};
%... your histogram code. Perfer histogram to hist
pngfilename = sprintf('hist%d_%d.png', outer, inner);
%... rest of export code
end
end
As Image Analyst suggest, you could avoid the cell arrays entirely, and store your data as an 80x400 matrix, which would make your life simpler, would use a lot less memory and be faster to process.