user3557054
user3557054

Reputation: 219

Get final variable for a code with loops on Matlab

I have a code with two for loops. The code is working properly. The problem is that at the end I would like to get a variable megafinal with the results for all the years. The original varaible A has 3M rows, so it gives me an error because the size of the megafinal changes with each loop iteration and matlab stops running the code. I guess it’s a problem of inefficiency. Does anyone know a way to get this final variable despite of the size?

y = 1997:2013;
for i=1:length(y)
    A=b(cell2mat(b(:,1))==y(i),:);
    %Obtain the absolute value of the difference
    c= cellfun(@minus,A(:,3),A(:,4));
    c=abs(c);
    c= num2cell(c);
    A(:,end+1) = c;
    %Delete rows based on a condition
    d = (abs(cell2mat(A(:,8)) - cell2mat(A(:,7))));
    [~, ind1] = sort(d);
    e= A(ind1(end:-1:1),:);
    [~, ind2,~] = unique(strcat(e(:,2),e(:, 6)));
    X= e(ind2,:);
    (…)
    for j = 2:length(X)
        if strcmp(X(j,2),X(j-1,2)) == 0
            lin2 = j-1;
            %Sort
            X(lin1:lin2,:) = sortrows(X(lin1:lin2,:),13);
            %Rank 
            [~,~,f]=unique([X{lin1:lin2,13}].');
            g=accumarray(f,(1:numel(f))',[],@mean);
            X(lin1:lin2,14)=num2cell(g(f));
            %Score
out1 = 100 - ((cell2mat(X(lin1:lin2,14))-1) ./ size(X(lin1:lin2,:),1))*100;
            X(lin1:lin2,15) = num2cell(out1);
            lin1 = j;
        end
    end
    %megafinal(i)=X
end

Upvotes: 0

Views: 51

Answers (1)

rayryeng
rayryeng

Reputation: 104503

Make megafinal a cell array. This will account for the varying sizes of X at each iteration. As such, simply do this:

megafinal{i} = X;

To access a cell element, you just have to do megafinal{num}, where num is any index you want.

Upvotes: 1

Related Questions