MATLAB: Extracting data from matrix: newbie question

matrix

I am new to matlab.
I am trying to use matlab for a psychology experiment. I obtained data in a matrix with two columns. The first column refers to the distance in cm and the second column to reaction time. The data matrix that I have looks something like this:
distance = [ 0.1 0.332;
0.2 0.678;
0.1 0.876;
0.3 0.765;
0 0.345;
0.2 0.541;
0.3 0.541;
0.1 0.567;
0.2 0.123;]
The distance (column 1) can be 0, 0.1, 0.2 or 0.3. I would like separate matrices for each of these distances (so I can compare their reaction times).
I wrote a for loop
S = 1;
T = 1;
U = 1;
V = 1;
for F = 1:length(distance)
if distance(F,1) == 0
distance_0(S,1) = distance(F,2);
S = S + 1;
elseif distance(F,1) == 0.1
distance_1(T) = distance(F,2);
T = T + 1;
elseif distance(F,1) == 0.2
distance_2(U) = distance(F,2);
U = U + 1;
else distance(F,1) == 0.3
distance_3(V) = distance(F,2);
V = V + 1;
end
end
The output should look like this:
distance_0 = [0.345]
distance_1 = [0.332; 0.876; 0.567]
distance_2 = [0.678; 0.541; 0.123]
distance_3 = [0.765; 0.541]
However, it is not working well and I don' t get the above output matrices. The matrices distance_* are only filled partly. What am I doing wrong! I hope someone can help me. Thanks in advance.

Best Answer

  • clear
    distance = [ 0.1 0.332;
    0.2 0.678;
    0.1 0.876;
    0.3 0.765;
    0 0.345;
    0.2 0.541;
    0.3 0.541;
    0.1 0.567;
    0.2 0.123;];
    %---------- ------------------------------------------------
    n=size(distance,1);
    S = 1;
    T = 1;
    U = 1;
    V = 1;
    for F = 1:n
    if distance(F,1) == 0
    distance_0(S,1) = distance(F,2);
    S = S + 1;
    elseif distance(F,1) == 0.1
    distance_1(T) = distance(F,2);
    T = T + 1;
    elseif distance(F,1) == 0.2
    distance_2(U) = distance(F,2);
    U = U + 1;
    elseif distance(F,1) == 0.3
    distance_3(V) = distance(F,2);
    V = V + 1;
    end
    end
    disp(distance_0)
    disp(distance_1)
    disp(distance_2)
    disp(distance_3)