MATLAB: How to create a matrix which fills each row with an array generated

arrays inside a matrixwhile loop

The ultimate goal is having the distance_result matrix to be filled with y rows and each row to be filled with x data (array). The first while loop generates the distance_result matrix and the second while loop takes care of the calculations for the distance array.
The problem is that the distance_result matrix has y rows that are all the same. For some reason the distance array is not changing with every iteration. Since y=y+1, then I expect the distance(x) to be changed for every new while loop for y.
Thank you!
clc
clear
x=1;
y=1;
p=1;
while (y<=1000) %y-axis
while (x<=1000) %x-axis
distance(x)=5*p*y*x;
x=x+1;
p=p+1;
end
distance_result(y,:)=distance; %a matrix storing all x-axis and y-axis outputs
y=y+1;
end

Best Answer

  • I think you're not initializing p and x at every new y value. Perhaps you meant this:
    y=1;
    while (y<=1000) %y-axis
    x=1;
    p=1;
    while (x<=1000) %x-axis
    distance(x)=5*p*y*x;
    x=x+1;
    p=p+1;
    end
    distance_result(y,:)=distance; %a matrix storing all x-axis and y-axis outputs
    y=y+1;
    end
    fprintf('Done!\n');
    imshow(distance_result, []);
    axis on;
    fontSize = 20;
    title('distance_result', 'FontSize', fontSize, 'Interpreter', 'none');
    xlabel('X', 'FontSize', fontSize);
    ylabel('Y', 'FontSize', fontSize);
    % Enlarge figure to full screen.
    set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0.05, 1, .95]);
    Of course in this case, you should be using a for loop instead of a while loop. Why did you choose to use a while loop???