Plotting content from structure

1 view (last 30 days)
Lukas Netzer
Lukas Netzer on 26 May 2021
Commented: Lukas Netzer on 26 May 2021
Hey, I am trying to plot values from a structure but somehow am getting Error using startswith.
Here is the code (examplified):
sges.location1 = 1;
sges.location2 = 2;
sges.location3 = 3,
sges.location4 = 4;
sges.location5 = 5;
sh.location1 = 4;
sh.location2 = 1;
sh.location3 = 2,
sh.location4 = 5;
sh.location5 = 3;
w1 = 0.6;
x = [1 2 3 4 5];
bar(x,sges,'FaceColor',[0.2 0.2 0.5])
ax = gca;
ax.YLabel.String = "Distance (km)"
title('Distance')
w2 = 0.5;
hold on
bar(x,sh,w2, 'FaceColor',[0 0.7 0.7])
grid on
legend({'sges', 'sh'}, 'Location', 'northwest')
labels = {'Loc1', 'Loc2', 'Loc3', 'Loc4', 'Loc5'};
set(gca, 'xtick', 1:5, 'XTickLabels', labels);
What am I doing wrong, am I missing something?

Accepted Answer

VBBV
VBBV on 26 May 2021
sges.location1 = 1;
sges.location2 = 2;
sges.location3 = 3,
sges = struct with fields:
location1: 1 location2: 2 location3: 3
sges.location4 = 4;
sges.location5 = 5;
sh.location1 = 4;
sh.location2 = 1;
sh.location3 = 2,
sh = struct with fields:
location1: 4 location2: 1 location3: 2
sh.location4 = 5;
sh.location5 = 3;
w1 = 0.6;
x = [1 2 3 4 5];
C = struct2cell(sges)
C = 5×1 cell array
{[1]} {[2]} {[3]} {[4]} {[5]}
cs = cell2mat(C)
cs = 5×1
1 2 3 4 5
H = struct2cell(sh)
H = 5×1 cell array
{[4]} {[1]} {[2]} {[5]} {[3]}
hs = cell2mat(H)
hs = 5×1
4 1 2 5 3
bar(x,cs,'FaceColor',[0.2 0.2 0.5])
ax = gca;
ax.YLabel.String = "Distance (km)"
ax =
Axes with properties: XLim: [-0.2000 6.2000] YLim: [0 5] XScale: 'linear' YScale: 'linear' GridLineStyle: '-' Position: [0.1300 0.1100 0.7750 0.8150] Units: 'normalized' Show all properties
title('Distance')
w2 = 0.5;
hold on
bar(x,hs,w2, 'FaceColor',[0 0.7 0.7])
grid on
legend({'sges', 'sh'}, 'Location', 'northwest')
labels = {'Loc1', 'Loc2', 'Loc3', 'Loc4', 'Loc5'};
set(gca, 'xtick', 1:5, 'XTickLabels', labels);
Use struct2cell and cell2mat for converting the struct array to double

More Answers (0)

Categories

Find more on Graphics Performance in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!