Can you explain the difference between the two matrix operations in MATLAB?

4 Ansichten (letzte 30 Tage)
I am trying to understand how MATLAB performs the following matrix operations:
Example 1:
clearvars; clc; close all;
Nx = 8;
Ny = 8;
Lx=2*pi;
dx = Lx/Nx;
Vec = fftshift(-Nx/2:Nx/2-1);
Vector1 = (sin( Vec * dx/2)/(dx/2)).^2 ;
[Matrix2,x] = cheb(Ny);
for m = 1:length(Vec)
Matrix1 = -1 * (Vector1(m))+ Matrix2;
end
Example 2:
clearvars; clc; close all;
Nx = 8;
Ny = 8;
Lx=2*pi;
dx = Lx/Nx;
Vec = fftshift(-Nx/2:Nx/2-1);
Vector1 = (sin( Vec * dx/2)/(dx/2)).^2 ;
Igl = speye(Ny+1);
[Matrix2,x] = cheb(Ny);
for m = 1:length(Vec)
Matrix1 = -Igl * (Vector1(m))+ Matrix2;
end
Why is Matrix1 different in Example1 and Example 2? In particular, in Example 1 how is the scalar multiplication of the row vector (Vector1(m)) added to Matrix 2? I am trying to understand the matrix operation done in Example 1 specifically so I can transfer it to C/C++. Thanks

Akzeptierte Antwort

Saurav
Saurav am 26 Jul. 2024
Hi Janee,
I see you want to understand how each example handles the multiplication and addition operations in a matrix.
Example 1:
  • The loop iterates through each element of Vec.
  • For each iteration, Matrix1 is set to -1 * (Vector1(m)) + Matrix2.
  • This means that during each iteration, Matrix1 is overwritten with the result of the scalar -1 * (Vector1(m)) added to the matrix Matrix2.
  • Because Matrix2 is a matrix and -1 * (Vector1(m)) is a scalar, MATLAB will broadcast the scalar across all elements of Matrix2. This effectively adds the scalar to each element of Matrix2.
Example 2:
  • The loop is similar, but this time -Igl * (Vector1(m)) is used instead of -1 * (Vector1(m)).
  • Here, Igl is the identity matrix of size (Ny+1) x (Ny+1).
  • When you multiply the scalar Vector1(m) by Igl, you get a diagonal matrix where each diagonal element is -Vector1(m).
  • This diagonal matrix is then added to Matrix2.
Key Differences:
  • Scalar Addition vs. Matrix Addition: In Example 1, a scalar is added to every element of Matrix2. In Example 2, a diagonal matrix (with -Vector1(m) on the diagonal) is added to Matrix2.
  • Resulting Matrix: In Example 1, Matrix1 is a matrix where each element is Matrix2(i,j) - Vector1(m). In Example 2, Matrix1 is a matrix where the diagonal elements are Matrix2(i,i) - Vector1(m) and the off-diagonal elements are the same as in Matrix2.
Refer to the following documentation to learn more about arrays and matrix operations:
Hope this helps!

Weitere Antworten (0)

Kategorien

Mehr zu Operating on Diagonal Matrices finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by