0

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.

1
  • You can often linearize a for loop with matlab, for example you can reach your goal with : eta.'.*ones(1,HN)*6 Commented Feb 19, 2019 at 11:18

2 Answers 2

1

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 ).';
Sign up to request clarification or add additional context in comments.

Comments

0

To answer your question as asked, you need to index on ii as well as v:

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

However this is in general a bad idea -- if you catch yourself using for-loops in MATLAB (particularly doubly-nested for-loops) you should consider if there might be a better way that uses MATLAB's strong vectorisation abilities.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.