Ather Cheema
Ather Cheema

Reputation: 416

How to store value of inner for loop in nested for loop in an array in Matlab?

pvec = 1:3;
    for i = 1:3
      p=pvec(i);
        for m = 1:p
        erfun=erfc(5/(2*sqrt(p-m)));
        suma(m) = sum(erfun)
        end
    end

I want to save sum of all values of erfun for every p i.e I want to have 3 values in final array but every value in the array should be sum of all the values of erfun for one p. Similar questions have been addressed but I could not apply them in my case.

Upvotes: 0

Views: 409

Answers (1)

dfrib
dfrib

Reputation: 73176

Minimal fix method (to your own code)

The following modification to your code will yield your requested results

suma = zeros(3,1);
pvec = 1:3;
for i = 1:3
  p=pvec(i);
  for m = 1:p
      erfun=erfc(5/(2*sqrt(p-m)));
      suma(i) = suma(i) + erfun;   %// <-- modified here
  end
end

Where I've also included suma = zeros(3,1), which I assume that you also have in your code (however not shown in your question); pre-allocating suma with sufficient entries.

Alternative method (arrayfun)

Another solution, you can make use of the arrayfun command to get rid of the inner for loop:

suma = zeros(1,3);
pvec = 1:3;
for i = 1:3
  p=pvec(i);
  suma(i) = sum(arrayfun(@(x) erfc(5/(2*sqrt(p-x))), 1:p));
end

Alternative method #2 (arrayfun)

An even more condensed solution, including also the purpose of the outer for loop in your arrayfun call:

suma = arrayfun(@(x) ...
    sum(erfc(5./(2*sqrt(kron(x, ones(1,x-1)) - 1:(x-1))))), pvec)

Here we've made use of the kron command, which will be implicitly used in the arrayfun command above as follows

kron(1, []) = [] %// empty array
kron(2, [1]) = 2
kron(3, [1 1]) = [3 3]

and used the fact that erfc addition from 1/sqrt(0) is always 0 (i.e., erfc(Inf) = 0, and hence we needn't evaluate the case m=p as it yields no addition to our sum).


Result

All of the above methods yield the result

suma =

         0
    0.0004
    0.0128

Upvotes: 1

Related Questions