Dear colleagues,
how can I plot data from a matrix and have the legend entries in it automatically, too?
To make my question easier to understand I attached a code snippet:
1) What works:
Matrix = [a, A_2, 0];
%% Plot
figure
hold on
for i=1:size(Matrix,1)
plot([0,Matrix(i,1)],[Matrix(i,2),Matrix(i,3)])
end
2) Waht I want to have:
Matrix = [a, A_2, 0, 'legend entry'];
%% Plot
figure
hold on
for i=1:size(Matrix,1)
plot([0,Matrix(i,1)],[Matrix(i,2),Matrix(i,3)])
legend(Matrix(i,4))
end
Can you please give me a hint?
Best regards
Felix

 Akzeptierte Antwort

Mehmed Saad
Mehmed Saad am 17 Apr. 2020

0 Stimmen

Cells are for that purpose, see help on cell
Matrix = {a, A_2, 0, 'legend entry'};
Matrix =
1×4 cell array
To access matrix first complete cell
Matrix{1,1}
it will give you a
if you want the first element of a you can access it using
Matrix{1,1}(1)

4 Kommentare

felix.b
felix.b am 17 Apr. 2020
Dear Muhammad,
thank you for your explanation and code. This works out good.
Do you happen to know how I can use the legend option properly?
If I use it in the "for loop" only one legend entry remains.
Best regards
Felix
felix.b
felix.b am 17 Apr. 2020
Bearbeitet: felix.b am 17 Apr. 2020
Perhaps I add the code snippet to explain my problem in an easier way:
Matrix = {a, b, c, 'legend 1';...
d, e, f, 'legend 2';...
g, h, i, 'legend 3'};
%% Plot
figure
hold on
for i=1:size(Matrix,1)
plot([0,Matrix{i,1}],[Matrix{i,2},Matrix{i,3}])
legend(Matrix{i,4})
end
hold off
grid on
figure
hold on
for i=1:size(Matrix,1)
plot([0,Matrix{i,1}],[Matrix{i,2},Matrix{i,3}])
end
legend(Matrix{:,4})
hold off
grid on
felix.b
felix.b am 20 Apr. 2020
Thank you very much, Muhammad! ( I don't know why I didn't see this solution myself.)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Produkte

Version

R2019a

Gefragt:

am 17 Apr. 2020

Kommentiert:

am 20 Apr. 2020

Community Treasure Hunt

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

Start Hunting!

Translated by