Search code examples
matlabfor-loopmatrixnested-loops

Nested for loop not outputing values for inner loop


I have a problem with this nested for loop:

eta = [1e-3:1e-2:9e-1];
HN =5;
for ii = 1:numel(eta)
    for v = 1:HN
        DeltaEta(v) = eta(ii)*6;
    end
end

This code gives the output of DeltaEta as a 1x5 vector.

However, I want the result to be 90x5 vector where DeltaEta is computed 5 times for each value of eta.

I believe the problem is with the way I am nesting the loops.

It seems trivial but I can't get the desired output, any leads would be appreciated.


Solution

  • You're assigning outputs to DeltaEta(v), where v = 1,2,..,HN. So you're only ever assigning to

    DeltaEta(1), DeltaEta(2), ..., DeltaEta(5)
    

    You can solve this with a 2D matrix output, indexing on ii too...

    eta = [1e-3:1e-2:9e-1];
    HN = 5;
    DeltaEta = NaN( numel(eta), HN );
    for ii = 1:numel(eta)
        for v = 1:HN
            DeltaEta(ii,v) = eta(ii)*6;
        end
    end
    % optional reshape at end to get column vector
    DeltaEta = DeltaEta(:);
    

    Note, there is no change within your inner loop - DeltaEta is the same for all values of v. That means you can get rid of the inner loop

    eta = [1e-3:1e-2:9e-1];
    HN = 5;
    DeltaEta = NaN( numel(eta), HN );
    for ii = 1:numel(eta)
        DeltaEta( ii, : ) = eta(ii) * 6;
    end
    

    And now we can see a way to actually remove the outer loop too

    eta = [1e-3:1e-2:9e-1];
    HN = 5;
    DeltaEta = repmat( eta*6, HN, 1 ).';