Changing line colors in nested for loop not working

3 vues (au cours des 30 derniers jours)
Davindra Usov
Davindra Usov le 26 Avr 2023
Modifié(e) : Rik le 26 Avr 2023
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

Réponses (1)

Rik
Rik le 26 Avr 2023
Modifié(e) : Rik le 26 Avr 2023
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

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by