Multiplication of elements in array in for loop
조회 수: 8 (최근 30일)
이전 댓글 표시
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
David Hill
2020년 4월 5일
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)?
답변 (1개)
Srivardhan Gadila
2020년 4월 8일
편집: Srivardhan Gadila
2020년 4월 10일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Import from MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!