Edgar Alfonso
Edgar Alfonso

Reputation: 685

How can I plot many vectors in the same graph using a loop 'for', matlab

How I can show in only one figure, several pairs of points x, y ? I've tried everything that I found on google, but in all cases only a single ordered pair of points x,y is shown.

Thank you.

pws = 2000;
q0EF = 500;
EF_vec = [0.2, 0.5, 0.8, 0.9];
hold all;
for k=1:length(EF_vec)
    if(EF_vec(k) <= 1)
        i = 1;
        clearvars y x;
        for pwfi=0:100:pws
            pwfp = pws - (pws - pwfi )*EF_vec(k);
            y(i) = pwfp;
            x(i) = q0EF * (1 - 0.2*(pwfp/pws) - 0.8*(pwfp/pws)^2 );
            i = i + 1;
        end
        plot(x, y); % this doesnt work. This only show only the lastest x,y values
    end
end

Upvotes: 0

Views: 78

Answers (3)

user1543042
user1543042

Reputation: 3440

Try using a cell array

pws = 2000;
q0EF = 500;
EF_vec = [0.2, 0.5, 0.8, 0.9];

X = cell(size(EF_vec));
Y = cell(size(EF_vec));

for k=1:length(EF_vec)
    if(EF_vec(k) <= 1)
        i = 1;
        clearvars y x;
        for pwfi=0:100:pws
            pwfp = pws - (pws - pwfi )*EF_vec(k);
            y(i) = pwfp;
            x(i) = q0EF * (1 - 0.2*(pwfp/pws) - 0.8*(pwfp/pws)^2 );
            i = i + 1;
        end
        X{k} = x;
        Y{k} = y;
    end
end

X(cellfun(@isempty, X)) = [];
Y(cellfun(@isempty, Y)) = [];

plot(X{:}, Y{:});

Upvotes: 0

rayryeng
rayryeng

Reputation: 104474

Use hold on to append more values onto your plot with multiple plot calls. I see you're using hold all, but that only works when there is a figure open. You have no figure open initially, so you need to do that. Therefore, spawn a new figure, use hold on, then use your code. It's also a good idea to plot all of your points as singular points. plot defaults to joining all of the points together by a straight line, so append a '.' as the third parameter to it:

pws = 2000;
q0EF = 500;
EF_vec = [0.2, 0.5, 0.8, 0.9];
figure; %// Change
hold on;
for k=1:length(EF_vec)
    if(EF_vec(k) <= 1)
        i = 1;
        clearvars y x;
        for pwfi=0:100:pws
            pwfp = pws - (pws - pwfi )*EF_vec(k);
            y(i) = pwfp;
            x(i) = q0EF * (1 - 0.2*(pwfp/pws) - 0.8*(pwfp/pws)^2 );
            i = i + 1;
        end
        plot(x, y, '.'); %// Change
    end
end

Upvotes: 2

ipa
ipa

Reputation: 1536

You can use plot(x, y, 'x'), which generates a scatter plot and use hold on to plot into the figure you should open before the for loops.

figure;
% looops
plot(x, y, 'x');
hold on

Your code works when I use it but you can't really see all curves as they are too close together. If you zoom in you can see them.

Upvotes: 0

Related Questions