calculate sum over n

8 views (last 30 days)
Ben Andersson
Ben Andersson on 16 Jul 2020
Commented: Ben Andersson on 22 Jul 2020
Hello! I try to calculate a sum over n of matrices K,L such as K(m,n)*L(n,t)*L(n,j). So far I have the code below, but I am doubing I wrote it correctly. Could you please give advise on that?
K=rand(20,20);
Ln=rand(20,20);
sum11=zeros(1,20);
for n=1:20
summ=K(:,n).*Ln(n,:).*Ln(n,:);
sum11(n)=sum11(n)+summ;
end
  4 Comments
Ben Andersson
Ben Andersson on 16 Jul 2020
sorry. The result must be an array, and I get a matrix.
K=rand(20,20);
Ln=rand(20,20);
sum11=zeros(1,20);
for n=1:20
summ=K(:,n).*Ln(n,:).*Ln(n,:);
sum11(n)=sum11(n)+summ;
end
Walter Roberson
Walter Roberson on 16 Jul 2020
K(:,n).*Ln(n,:).*Ln(n,:)
is
K(:,n).*Ln(n,:).^2
Are you sure that is what you want? K(:,n) would be 20 x 1, and Ln(n,:).^2 would be 1 x 20, and 20 x 1 .* 1 x 20 is going to give you a 20 x 20 result.

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 16 Jul 2020
Why not just try:
K = rand(20, 20);
Ln = rand(20, 20);
n = 5; % Whatever.
% Compute the matrix product of
% a 5 matrix by a 5 matrix
% to get a 20x20 matrix.
LSquared = Ln .^ 2;
theProduct = K(:, 1:n) * LSquared(1:n, :)
% Now sum up.
theSum = sum(theProduct(:))
Unless you have specific numbers for t and j, then it would be different.
  4 Comments
Image Analyst
Image Analyst on 16 Jul 2020
Why would it be a vector? For a given, specified t, j, and m, you're multiplying single elements together to get a single number, and summing them up. This is what I get using your new formula you edited and placed in your original post:
% Declare constants for t, j, and m
m = 10;
t = 2;
j = 3;
% Define two 20-by-20 matrices.
K = rand(20, 20);
L = rand(20, 20);
% Make sure n is not greater than the number of columns in K
% or the number of rows in L
maxIndex = min([size(K, 2), size(L, 1)])
theSum = 0;
for n = 1 : maxIndex
LntLnj = L(n, t) .* L(n, j);
thisKelement = K(m, n);
theProduct = thisKelement * LntLnj;
theSum = theSum + theProduct;
end
theSum % Show result in command window.
Ben Andersson
Ben Andersson on 22 Jul 2020
Thanks!

Sign in to comment.

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!