0

I'm trying to calculate an array but my for loop produces the numbers individually and then saves the last output as the vector can you please help? My code is:

for k= 0:0.1:3
muk = [nanmean(abs(normGsf).^(k))] 
end

The output I am seening is

muk =

 1

muk =

0.9169

muk =

0.8520

muk =

0.8011

muk =

0.7616

muk =

0.7314

muk =

0.7089

muk =

0.6932

muk =

0.6836

muk =

0.6794

muk =

0.6805

muk =

0.6866

muk =

0.6976

muk =

0.7138

muk =

0.7351

muk =

0.7621

muk =

0.7950

muk =

0.8345

muk =

0.8812

muk =

0.9359

muk =

0.9996

muk =

1.0736

muk =

1.1592

muk =

1.2582

muk =

1.3724

muk =

1.5043

muk =

1.6567

muk =

1.8327

muk =

2.0362

muk =

2.2719

muk =

2.5450
1
  • ind = 1; for k= 0:0.1:3, muk(ind) = [nanmean(abs(normGsf).^(k))]; ind= ind+1;end or for k= 0:0.1:3, muk(k*10+1) = [nanmean(abs(normGsf).^(k))];end Commented Mar 26, 2014 at 14:47

2 Answers 2

1

Why not vectorize?

k = 0:0.1:3;
muk = nanmean(abs(normGsf)).^k;

I'm assuming nanmean(abs(normGsf)) is a scalar, as in your example. Then the result muk is a vector with the same size as k.

Sign up to request clarification or add additional context in comments.

Comments

0

You could do something like this:

muk = [];    
for k= 0:0.1:3
muk = [muk; nanmean(abs(normGsf).^(k))] 
end

This appends the new values to "muk" each time through the loop. Note that this is not necessarily a good practice if the number of loop iterations is really large, but you are far, far from that limit.

1 Comment

Note that this is very inefficient, since you're creating a "growing matrix". It's much better to preallocate memory and "fill" it up afterwards. If you want to keep the loop, muk = zeros(31,1); for k = 0:0.1:3 -- muk(k) = nanmean(abs(normGsf).^(k)); -- end. However, Luis' vectorized approach is even better =)

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.