Miro Feliciano
Miro Feliciano

Reputation: 79

Using a for-loop to plot several values in the same figure

I am trying to plot a gravity anomaly by a method of trial and error in a for loop. I have below the formula for a gravity anomaly gal1 caused by a round body, and I am trying to change the values of the mass (m) and the depth of the center of gravity (h) in the loop, so that it plots each value of the gravity anomaly for the different m and h inserted.

What happens is it does not plot any values using plot(x,gal1(j) and only plots one value when I do plot(x,gal1). What I expect is for it to plot the values for each iteration in the loop so that I have various plots for different gal1

x=[-3 ; -2.5; -2; -1.5; -1; -0.5; 0; 0.5; 1.5];
    for j=1:9
        for i = 10:10:90
            for k = 10:10:90
                h(i)=i/100;
                m(k)=k/100
                gal1(j)=(6.67 * (m(k)) * (h(i))/(x(j, 1)^2 + (h(i)) ^2)^(3/2));
                plot(x,gal1(j))
                hold on
            end
        end
    end

Upvotes: 0

Views: 96

Answers (1)

Adriaan
Adriaan

Reputation: 18187

The problem is, as Adam mentioned that you are plotting a single point every time versus a complete array, thus it resulted in an error. Instead, calculate the whole array gal1 and then plot it in its entirety.

x=[-3 ; -2.5; -2; -1.5; -1; -0.5; 0; 0.5; 1.5];
for j=1:9
    for i = 10:10:90
        for k = 10:10:90
            h(i)=i/100;
            m(k)=k/100;
            gal1(j)=(6.67 * (m(k)) * (h(i))/(x(j, 1)^2 + (h(i)) ^2)^(3/2));
        end
    end
end

figure;
plot(x,gal1,'-o') % - means a line, o gives dots on each measurement

Results in:

enter image description here


All those loops are overly verbose, difficult to read, easy to make errors in, and probably slower than a simple, vectorised, calculation:

x=[-3 ; -2.5; -2; -1.5; -1; -0.5; 0; 0.5; 1.5];
h = (0.1:0.1:0.9).';
m = (0.1:0.1:0.9).'; % =h?

gal1 = 6.67.*m.*h./((x.^2+h.^2).^(3/2));

figure;
plot(x,gal1,'-o')  % Same figure as above

Note that you create h and m before hand (they are equal though in this case?), be sure to transpose them to column vectors, just like you have x. Then simply use the same formula for gal1, and drop all indexing and replace operators by their element-wise counterparts by adding the dot in front of all the *, /, ^ operators.

Using a bit of implicit-expansion magic, you can even plot all combinations of h and m directly:

x=[-3 ; -2.5; -2; -1.5; -1; -0.5; 0; 0.5; 1.5];
h = (0.1:0.1:0.9).';
m = (0.1:0.1:0.9); DO NOT transpose this

gal1 = 6.67.*m.*h./((x.^2+h.^2).^(3/2)); % is now 9x9

figure;
plot(x,gal1,'-o')
legend

Giving a plot for each column, i.e. differing h value:

enter image description here

Upvotes: 2

Related Questions