0

I am trying to put the following data from my for loop into a table formatted so that there are 11 values of F in each column, with a total of 4 columns.

but I am always ending up with one long column of my data instead of the four columns I want. I was wondering if there is some way to put the data into a matrix and then reshape it, but I am having trouble. Any help greatly appreciated.

fprintf ('Electrostatic Forces:\n')
 for  r = 1:4;
    q2 = 0: 1*10^-19: 1*10^-18;
        for F = coulomb(q2,r);
            fprintf ('%d\n',F)
    end
end

Where the code for the function coulomb is

function F = coulomb (q2,r);
k = 8.98*10^9;
q1 = 1.6*10^-19;
F = k*abs(q1*q2)/r^2;

end

1 Answer 1

2

One way to do it is the following:

fprintf ('Electrostatic Forces:\n')
q2 = 0: 1*10^-19: 1*10^-18;
for h = 1:numel(q2);

    % Coulomb function
    k = 8.98*10^9;
    q1 = 1.6*10^-19;
    F = k * abs(q1 * q2(h))./[1:4].^2;

    for r = 1:4;
        fprintf('%d ', F(r))
    end
    fprintf('\n')
end

Another way is to redefine your function as

function F = coulomb (q2, r);
k = 8.98 * 10 ^ 9;
q1 = 1.6 * 10 ^ -19;
F = k * abs(q1 * repmat(q2(:)', numel(r), 1)) ./ (repmat(r(:), 1, numel(q2)) .^ 2);

Then you can just type

q2 = 0: 1*10^-19: 1*10^-18;
r = 1:4;
F = coulomb(q2, r)'

and you will have your table.

Sign up to request clarification or add additional context in comments.

4 Comments

The output I get from that is;0 1.436800e-28 2.873600e-28 4.310400e-28 5.747200e-28 7.184000e-28 8.620800e-28 1.005760e-27 1.149440e-27 1.293120e-27 1.436800e-27 0 3.592000e-29 7.184000e-29 1.077600e-28 1.436800e-28 1.796000e-28 2.155200e-28 2.514400e-28 2.873600e-28 3.232800e-28 3.592000e-28 0 1.596444e-29 3.192889e-29 4.789333e-29 6.385778e-29 7.982222e-29 9.578667e-29 1.117511e-28 1.277156e-28 1.436800e-28 1.596444e-28 0 8.980000e-30 1.796000e-29 2.694000e-29 3.592000e-29 4.490000e-29 5.388000e-29 6.286000e-29 7.184000e-29 8.082000e-29 8.980000e-29 only the rows should be the columns
I don't understand: you want that table transposed?
I have now produced the transposed table.
If the answer is OK you can consider accepting it (by clicking on the green check mark symbol).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.