Multiplication of elements in array in for loop

조회 수: 8 (최근 30일)
EraGum
EraGum 2020년 4월 5일
댓글: Srivardhan Gadila 2020년 4월 10일
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
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)?
EraGum
EraGum 2020년 4월 6일
Yes, A1 is A(1:29), A2 is A(2:29) and etc.
mu and sigma were calculated using the data from columns E and G.
e.g.
mu(i)=k(i)*(E_data(i)^x(i))*(G_data(i)^y(i));
k, x and y are "calibration parameters''.
In the question I tried to simplify my code so it wouldn't look too confusing.

댓글을 달려면 로그인하십시오.

답변 (1개)

Srivardhan Gadila
Srivardhan Gadila 2020년 4월 8일
편집: Srivardhan Gadila 2020년 4월 10일
Refer to arrayfun and use it as follows:
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
  댓글 수: 2
EraGum
EraGum 2020년 4월 10일
Thank you for reply. I used your advice and changed my code to:
AiArray=xlsread('NACA_data.xlsx',1,'A1:A29');
for i=1:length(AiArray)
prob(i)=prod(arrayfun(@(Ai)normpdf(Ai, mu(i), sigma(i)),AiArray));
end
However, I keep geeting prob as 0.
Did I understand you right?
Srivardhan Gadila
Srivardhan Gadila 2020년 4월 10일
@EraGum, I have edited the answer and provided example code for clarity.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Data Import from MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by