Changing line colors in nested for loop not working

1 次查看(过去 30 天)
Hi there,
I am struggling to change line and marker colors in this nested for loop:
col = {'r', 'b'};
sym = {A, B};
Unrecognized function or variable 'A'.
x = [20 30 40 50];
matrix_A = [1 2 3 4; 5 6 7 8];
matrix_B = [9 10 11 12; 13 14 15 16];
figure
fig = tiledlayout(1,2)
for i = 1:length(sym)
t1 = nexttile(fig);
for j = 1:length(col)
plot(t1, x, eval(['matrix_' sym{i}]), 'color', col{j}); % plotting matrix_A and matrix_B
end
end
This nested loop plots 2 blue lines instead of a red and a blue
Thank you all

回答(1 个)

Rik
Rik 2023-4-26
编辑:Rik 2023-4-26
Why are you using eval? There is no real reason you should need it. Same goes for length: what you actually mean is numel (or perhaps size).
Anyway, the cause for this problem is that you are plotting your data twice, first with red and then with blue. You are not changing the color for each row of your data.
matrix_A = [1 2 3 4; 5 6 7 8];
matrix_B = [9 10 11 12; 13 14 15 16];
col = {'r', 'b'};
data = {matrix_A, matrix_B};
x = [20 30 40 50];
figure
fig = tiledlayout(1,2);
for i = 1:numel(data)
t1 = nexttile(fig);
for data_row = 1:size(data{i},1)
plot(t1, x, data{i}(data_row,:), 'color', col{data_row});
hold(t1,'on')
end
end

类别

Help CenterFile Exchange 中查找有关 Annotations 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by