MATLAB: How to use loop to use a range of values

for looprange

Hi I have this peice of code where, I need to calcuate A for changing x0 and v0 values. In this for loop it changes x0 and v0 simultaneously. Can you help me to figure out how to change both variables 1 at a time. I want to do a surface plot of A vs x0 and v0. A has to be 21*21 matrix. I am able to only fill 1 row or column. I do not want to write 21 for loops to fill all the 21 columns. any way to do this without the long code ? if i change the resolution of x0 and v0 it goes to 201 columns. Please advise
wn = 10;
x0 = (-0.1:0.01:0.1)';
v0 = (-1:0.1:1)';
A = zeros(numel(x0),numel(v0))';
for i = 1:numel(x0)
A(i) = (sqrt(wn^2*x0(i)^2+v0(i)^2)/wn);
end

Best Answer

  • You could use nested loops, one for ‘x0‘ and another one for ‘v0’, or you coud do it the easy way, using vectorized code for ‘A’ and ndgrid to calculate the matrices:
    [X0,V0] = ndgrid(x0,v0);
    A = (sqrt(wn^2*X0.^2+V0.^2)/wn);
    figure
    surfc(X0, V0, A)
    grid on
    xlabel('x_0')
    ylabel('v_0')
    zlabel('A')
    The nested loop approach would be:
    for i = 1:numel(x0)
    for k = 1:numel(v0)
    A(i,k) = (sqrt(wn^2*x0(i)^2+v0(k)^2)/wn);
    end
    end
    The ndgrid approach with vectorisation is more efficient.