Using a for loop to graph values using different colors

6 vues (au cours des 30 derniers jours)
Mariana Lugo
Mariana Lugo le 13 Avr 2020
Commenté : Stephen23 le 14 Avr 2020
I'm using some distances and I want to plot them. On my plot they should have a different color depending on how far away the are. Right now when I run my code, they're all being displayed with the same color. How can I make my distances different colors depending on their distance?
clear all
close all
data = [3 24 30 26 22 14 15 7 5 9];
t = (1:length(data));
for i = 1:length(data);
if data(data <= 30 & data > 20)
scatter(t,data,'.g');
hold on;
elseif data(data <= 20 & data > 10)
scatter(t,data,'.y');
hold on;
elseif data(data <= 10 & data >= 0)
scatter(t,data,'.r');
hold on;
end
xlabel('time (seconds)')
xlim([0 13])
ylabel('distance(meters)')
ylim([0 35])
title('Distance of Vehicle Over Time')
end

Réponse acceptée

Ameer Hamza
Ameer Hamza le 13 Avr 2020
Modifié(e) : Ameer Hamza le 13 Avr 2020
There were issues with the if conditions. Check the corrected code. Also, note that you were plotting to scatter plot with all points.
clear all
close all
data = [3 24 30 26 22 14 15 7 5 9];
t = (1:length(data));
for i = 1:length(data)
if data(data(i) <= 30 & data(i) > 20)
scatter(t(i),data(i),'+b', 'Linewidth', 2);
hold on;
elseif data(data(i) <= 20 & data(i) > 10)
scatter(t(i),data(i),'+m', 'Linewidth', 2);
hold on;
elseif data(data(i) <= 10 & data(i) >= 0)
scatter(t(i),data(i),'+r', 'Linewidth', 2);
hold on;
end
xlabel('time (seconds)')
xlim([0 13])
ylabel('distance(meters)')
ylim([0 35])
title('Distance of Vehicle Over Time')
end

Plus de réponses (1)

Turlough Hughes
Turlough Hughes le 13 Avr 2020
Modifié(e) : Turlough Hughes le 13 Avr 2020
If you want to use scatter so that the color depends on distance, this is how you do it:
% Data
clear all
close all
data = [3 24 30 26 22 14 15 7 5 9];
t = (1:length(data));
scatter(t,data,[],data,'filled') % < modified code
xlabel('time (seconds)')
xlim([0 13])
ylabel('distance(meters)')
ylim([0 35])
title('Distance of Vehicle Over Time')
If you specifically require 3 colors, you have the option of setting the colormap with just three sets of color triplets as follows:
colormap([1 0 0; 0 1 0; 0 0 1])
See documentation for scatter and colormap.

Catégories

En savoir plus sur Line Plots dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by