# Bar diagram as subplot in a for loop from a cell

2 views (last 30 days)
Patrick Petre on 28 Nov 2020
Commented: Patrick Petre on 29 Nov 2020
So i have a for loop which calculates some data and after i plot everything i want a subplot as a bar diagramm. I fit a linear curve to my data and want the gradient of the linear regression as the bar value. for each dataset is should take out the first value. If i try it with a simple example as at the end with a and b(i) it works fine but my bar diagramm only shows the value of p{1,1}(1) with the color of c{2} ? I am so confused and thankful for evey help.
number = numel(data)
for i = 1:number
p{i} = polyfit(x_relevant{i}, y_relevant{i},1)
subplot(4,1,4)
b(i) = bar(p{1,i}(1),'FaceColor',c{i}) % each data set, take out first value
hold on
a = {[1 2], [3 4]}
b(i) = a{1,i}(1)
end

Adam Danz on 28 Nov 2020
Edited: Adam Danz on 28 Nov 2020
The goal is unclear but I think this is what your looking for,
number = numel(data);
for i = 1:number
p{i} = polyfit(x_relevant{i}, y_relevant{i},1);
end
coefs = cell2mat(p(:));
subplot(4,1,4)
b = bar(coefs(:,1));
bh.FaceColor = 'flat';
bh.CData = c; % where c is something like c=jet(numel(b.XData));
If not, please provide more details.

Patrick Petre on 28 Nov 2020
Yes thats exactly what i was looking for. Could you explain why my approach was wrong or didnt work?
Adam Danz on 28 Nov 2020
I'd be happy to.
The main idea is to use the loop to gather the data and then organize the data into a matrix rather that using the loop to do the plotting. If you want a single bar plot with n-bars, you need a vector of n-values. Instead, your vector only contained 1 value on each iteration and you were merely adding another bar on top of the existing bars at x=1.
number = numel(data); % <--- minor, but add semicolon suppression
for i = 1:number
p{i} = polyfit(x_relevant{i}, y_relevant{i},1)
subplot(4,1,4) % <--- not necessary to call within the loop
b(i) = bar(p{1,i}(1),'FaceColor',c{i}) % <--- **All bars will be at x=1, on top of each other
hold on % <--- not necessary at all
a = {[1 2], [3 4]} % <--- ??? this is a mystery to me
b(i) = a{1,i}(1) % <--- ??? this is a mystery to me
end
Patrick Petre on 29 Nov 2020
The last 2 rows was to test the syntax and the b(i) actually contained the values 1 and 3 after running the for loop. Thats why i was confused why my bar plot only contains one value.
On the other hand.. while running the for loop each loop contains one color stored in c which gives all the plots from one set of data the same color.