Multiplication of elements in array in for loop
8 views (last 30 days)
Show older comments
Hello,
I need an advice how can I shorten my code. I feel like it should be a very easy thing to do but can't think of anything.
For my code I am using three columns of data from excel spreadsheet, e.g. column A, E and G. Each column has 29 rows.
The code has a FOR loop, which determines the probability estimation. The line, which concerns me is:
prob(i)=normpdf(A1(i),mu(i),sigma(i))*normpdf(A2(i),mu(i),sigma(i))*normpdf(A3(i),mu(i),sigma(i))... *normpdf (A29(i), mu(i), sigma(i)) ;
Is there any way that could help me to shorten the whole line and do 29 multiplications automatically?
Could I write something like this?
prob(i)=prod(normpdf(A_data(i), mu(i), sigma(i)))
2 Comments
David Hill
on 5 Apr 2020
I don't understand. What is A1....A29 is that A(1:29)? What is mu and sigma? Are they E(1:29) and G(1:29)?
Answers (1)
Srivardhan Gadila
on 8 Apr 2020
Edited: Srivardhan Gadila
on 10 Apr 2020
Let all the A1(i), A2(i) ... A29(i) be in the array AiArray
prob(i)=prod(arrayfun(@(Ai)normpdf(Ai, mu(i), sigma(i)),AiArray))
The following code might help you understand:
N = 5; %i=1:N
mu = randn(N,1);
sigma = abs(randn(N,1));
A1 = randn(N,1);
A2 = randn(N,1);
A3 = randn(N,1);
A1Array = [A1(1);A2(1);A3(1)];
A2Array = [A1(2);A2(2);A3(2)];
A3Array = [A1(3);A2(3);A3(3)];
A4Array = [A1(4);A2(4);A3(4)];
A5Array = [A1(5);A2(5);A3(5)];
% The above AiArray's are defined only to understand what I'm trying to explain
Amatrix = [A1 A2 A3];
prob = [];
for i=1:N
prob(i)=prod(arrayfun(@(Ai)normpdf(Ai, mu(i), sigma(i)),Amatrix(i,:)));
end
See Also
Categories
Find more on Data Import from MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!