Carl
Carl

Reputation: 149

How to plot the first point of each vector in MATLAB

I have 8 vectors in MATLAB with dimension 1x18 which I have calculated like this:

i = 19
for c = 1:i
    rpm_new(c) = c*250;
end

for c = 1:i-1
    lambda_avg(c) = mean(sw1.Lambda((sw1.RPM >=rpm_new(c)) & sw1.RPM < rpm_new(c+1)));
    lambda_avg2(c) = mean(sw2.Lambda((sw2.RPM >=rpm_new(c)) & sw2.RPM < rpm_new(c+1)));
    lambda_avg3(c) = mean(sw3.Lambda((sw3.RPM >=rpm_new(c)) & sw3.RPM < rpm_new(c+1)));
    lambda_avg4(c) = mean(sw4.Lambda((sw4.RPM >=rpm_new(c)) & sw4.RPM < rpm_new(c+1)));
    lambda_avg5(c) = mean(sw5.Lambda((sw5.RPM >=rpm_new(c)) & sw5.RPM < rpm_new(c+1)));
    lambda_avg6(c) = mean(sw6.Lambda((sw6.RPM >=rpm_new(c)) & sw6.RPM < rpm_new(c+1)));
    lambda_avg7(c) = mean(sw7.Lambda((sw7.RPM >=rpm_new(c)) & sw7.RPM < rpm_new(c+1)));
    lambda_avg8(c) = mean(sw8.Lambda((sw8.RPM >=rpm_new(c)) & sw8.RPM < rpm_new(c+1)));
end

Now, I want to be able to plot the first element of each vector at x-coordinate 1, so something

scatter(1,lambda_avg(1))
hold on
scatter(1,lambda_avg2(1))
...

I then want to plot the second element of each vector at x-coordinate 2, so something like

scatter(2,lambda_avg(2))
hold on
scatter(2,lambda_avg2(2))
...

Is it possible to do this in a smart way, and to do it in a single plot? Would it also be possible to connect each point in a vector together? Such that all the points from lambda_avg is connected by a line and the same for lambda_avg2?

Upvotes: 0

Views: 94

Answers (1)

Wolfie
Wolfie

Reputation: 30047

Use a matrix to store your results instead of individual vectors.

A neater way is to also use a 2nd loop (this relies on you also using sw.Lambda1, sw.Lambda2, ... instead of sw1.Lambda, sw2.Lambda, ..., which is a better option). You could use 8 individual lines to assign the rows of the matrix if you wanted though.

lambda_avg = zeros(8,i-1);
for r = 1:8
    swr = sw.(['Lambda' num2str(r)]); % sw.Lambda1, sw.Lambda2, ...
    for c = 1:i-1
        lambda_avg(r,c) = mean(swr.Lambda((swr.RPM >=rpm_new(c)) & swr.RPM < rpm_new(c+1))); 
    end       
end

Then it's much easier to plot things, using a single call and without needing hold.

plot( 1:8, lambda_avg, '.k' );

Note that you could probably vectorise this further to remove at least one of the two loops, but that's beyond the scope of this question really as it requires changes to your earlier code. Read more about MATLAB vectorisation in the docs here.

Upvotes: 3

Related Questions