Multiplication of elements in array in for loop

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 个评论

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)?
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 个)

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 个评论

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?
@EraGum, I have edited the answer and provided example code for clarity.

请先登录,再进行评论。

类别

帮助中心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!

Translated by