Markus Vietze
Markus Vietze

Reputation: 17

Count results of for-if/else-statements and write it in matrix

I want to store in my code the results of the for loop (starting with "for o = 1:length(gwi)"), how often which statement("<a", ">=a & <b", ....) was used, in a matrix. I have tried to record this numerically (1-4) for the value "Liste2". But now I have the problem that I don't know how to do this for all 722 iterations (k) of the big for loop, so that at the end I get one column of a matrix for each of the 722 iterations. Also, unfortunately, the lengths of the arrays vary.

The (simplified) code follows:

for k = 1:722
    gwi = abs(wi);
    Liste = zeros(length(gwi),1);
    Liste2 = zeros(length(gwi),1);
    for o = 1:length(gwi)
        if gwi(o) < a;
           Liste(o) = 1;
           Liste2(o) = 1;
        elseif gwi(o) >= a & gwi(o) < b;
           Liste(o) = a / gwi(o);
           Liste2(o) = 2;
        elseif gwi(o) >= b & gwi(o) < c;
           Liste(o) =  a * ((c-gwi(o))/((c-b)*gwi(o)));
           Liste2(o) = 3;  
        else gwi(o) >= c;
           Liste(o) = 0;
           Liste2(o) = 4;   
        end
    end
end 

Upvotes: 0

Views: 48

Answers (1)

Wolfie
Wolfie

Reputation: 30046

You can store Liste and Liste2 as 2D matrices instead of arrays, so

% Initialise List matrices before both loops
gwi = abs(wi);
N = 722;
Liste = zeros(length(gwi),N);  % Note "N" columns
Liste2 = zeros(length(gwi),N); % Note "N" columns

for k = 1:722
    for o = 1:length(gwi)
        if condition1
            Liste(o,k) = sin(o); % some calculation for condition 1
            Liste2(o,k) = 1;     % Condition number for index (o,k)
        elseif condition2
            Liste(o,k) = exp(o); % some calculation for condition 2
            Liste2(o,k) = 2;     % Condition number for index (o,k)
        % elseif ...
        end
    end
end

Your result would be matrices where each column corresponds to a k loop, and each row corresponds to the o value.

Upvotes: 1

Related Questions