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

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

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

 채택된 답변

Image Analyst
Image Analyst 2020년 7월 16일

0 개 추천

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

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

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 MATLAB에 대해 자세히 알아보기

태그

질문:

2020년 7월 16일

댓글:

2020년 7월 22일

Community Treasure Hunt

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

Start Hunting!

Translated by