matlabpsychtoolbox

How to store two variables (x.y) from a loop?


I am generating two different coordinates (x, y) within a loop. In my code, I have just realised that it is saving the last variable from the loop. I am, however, trying to save all the iterations from the setsize variable. I already tried to save using something like:

circleposition = [0:length(setsize) x(i),y(i)]; 

But, it seems that I am not doing it correctly, getting the following error:

Subscript indices must either be real positive integers or logicals.- 
Error using vertcat
Dimensions of matrices being concatenated are not consistent.

Here is my original code:

setsize = 9; 
r = 340;
cx = 500;
cy = 500;
anglesegment = 2 * pi/setsize;
circleposition = []; 

for i = drange (0:setsize)
    x = r * cos(i*anglesegment) + cx;
    y = r * sin(i*anglesegment) + cy;
    circleposition = [x,y];
end 

Output:

circleposition =
             0    1.0000
      840.0000  500.0000

It runs only with the first/last iteration. I need to get 9 x's and 9 y's (depending the setsize, variable).


Solution

  • It's kind of hard to follow, which error message comes from which attempt, but let's have a look.

    I don't have access to the Parallel Computing Toolbox, which seems necessary to use the for-loop over distributed range drange, but I assume, this loop can be replaced by for i = 0:setsize for testing.

    Now, when starting at i = 0, you would try to access x(0) and y(0), which is not allowed (Subscript indices must either be real positive integers or logicals). Also, you would get 10 values instead of 9, as you stated in your question. So, let's start at i = 1.

    To store all 9 pairs of x and y, your circleposition should be an 9 x 2 array So, initialize that by, for example, circleposition = zeros(setsize, 2).

    Last, you need to use proper indexing to store [x, y] at the i-th row of circleposition, i.e. circleposition(i, :).

    So, the corrected code (attention on the replaced drange part) could look like this:

    setsize = 9; 
    r = 340;
    cx = 500;
    cy = 500;
    anglesegment = 2 * pi/setsize;
    circleposition = zeros(setsize, 2);     % Initialize circleposition appropriately
    
    for i = 1:setsize                       % Start at i = 1
        x = r * cos(i*anglesegment) + cx;
        y = r * sin(i*anglesegment) + cy;
        circleposition(i, :) = [x, y];      % Correct indexing of the row
    end 
    
    circleposition                          % Output
    

    The output would then be:

    circleposition =
       760.46   718.55
       559.04   834.83
       330.00   794.45
       180.50   616.29
       180.50   383.71
       330.00   205.55
       559.04   165.17
       760.46   281.45
       840.00   500.00
    

    On the second error (Error using vertcat. Dimensions of matrices being concatenated are not consistent.): I don't see, where you used vertical concatenation at all!?