- 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?
3 views (last 30 days)
Show older comments
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 Comment
Abhishek Gupta
on 15 Feb 2021
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.
Answers (1)
Abhishek Gupta
on 15 Feb 2021
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
See Also
Categories
Find more on Operating on Diagonal Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!