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 commentaires

KSSV
KSSV le 16 Juil 2020
Is the given code working first?
Walter Roberson
Walter Roberson le 16 Juil 2020
You should not have the period between K and the (
nn is not defined.
Ben Andersson
Ben Andersson le 16 Juil 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 le 16 Juil 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.

Connectez-vous pour commenter.

 Réponse acceptée

Image Analyst
Image Analyst le 16 Juil 2020

0 votes

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 commentaires

Ben Andersson
Ben Andersson le 16 Juil 2020
thanks, but it gives me one number and not a vector. I confused array with the vector above.
Ben Andersson
Ben Andersson le 16 Juil 2020
then something like this should be, right?
sum(theProduct(1:n,:))
Image Analyst
Image Analyst le 16 Juil 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 le 22 Juil 2020
Thanks!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur MATLAB dans Centre d'aide et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by