- Your output matrix, i.e., A, contains the value for the second term of the equation, right? If so, then Is 'Vec' in the code corresponds to the 'Sn' in the equation? Also, I don't see any (-1/2) term in your code.
- What is your final object? Do you want to avoid filling the first row and first column of the matrix?
- Do you also want to avoid diagonal cells of the matrix? From '/,' you mean NaN?
How do I make this sum loop work to fill select matrix elements?
조회 수: 2 (최근 30일)
이전 댓글 표시
I have a summation loop which is within a nested loop to generate a matrix. I'm not sure how to make it work properly for a start, and then only fill cells which are not on row 1, or column 1.
The code so far is
close all
clear
clc
n = 5;
n_pot = 5;
Vec = [1,1,1,1,1,1,1]
syms k
Sum = sum(Vec,1:n)
Vt = zeros(1,n);
V_sum = zeros(1,n);
A = zeros(n);
for rows = 1:n
for cols = 1:n
for i = 1:n_pot
Vt(i) = Vt(i) + (Vec(i)*(Kron(rows+cols,i) + Kron(abs(cols-rows),i)));
V_sum = Vt(i);
A(rows,cols) = V_sum
end
end
end
function d = Kron(k,j)
if k == j
d = 1;
else
d = 0;
end
end
The Vec vector is only there for ease of manipulation on my part and will be replaced with a regular vector from graph fitting data.
The matrix I'm expecting to get is of the form
Matrix = / / / / /
/ / Vec(1)+Vec(3) Vec(2)+Vec(3) Vec(3)+Vec(5)
/ Vec(1)+Vec(3) / Vec(1)+Vec(5) Vec(2)+Vec(6)
/ Vec(2)+Vec(3) Vec(1)+Vec(5) / Vec(1)
/ Vec(3)+Vec(5) Vec(2)+Vec(6) Vec(1) /
Following this equation, I'm looking to implement the summation portion, and the first term is already worked in.
댓글 수: 1
Abhishek Gupta
2021년 2월 15일
Can you provide the following clarifications?
If you want to solve the second term of the given equation avoiding m and m' corresponding to the first row, first column, and diagonal cells of the matrix, see the answer below.
답변 (1개)
Abhishek Gupta
2021년 2월 15일
Hi,
As per my current understanding, you want to solve the second term of the equation, avoiding m and m' corresponding to the first row, first column, and diagonal elements of the matrix.
Here is the implementation of the same: -
A = nan(n); % output matrix
for rows = 1:n
for cols = 1:n
% if statement to avoid filling 1st row, 1st column, and diagonal elements
if ~((rows == 1) || (cols == 1) || (rows == cols))
secondTerm = 0; % initialize second term of the equation
% calculate the second term
for i = 1:n_pot
secondTerm = secondTerm + (Vec(i)*(Kron(rows+cols,i) + Kron(abs(cols-rows),i)));
end
A(rows,cols) = (-1/2)*secondTerm;
end
end
end
참고 항목
카테고리
Help Center 및 File Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!