forming a matrix with given entries

1 次查看(过去 30 天)
MADHVI
MADHVI 2023-11-4
评论: MADHVI 2023-12-20
correct the use of if condition in the following code:
function [A,B] = fdm1(H,xi,a,b,N)
H = 1; xi = 0.1;
a= -1; b = 1; N=5;
h = (b-a)/N; h2 = h*h;
A = zeros(20*(N-1),20*(N-1));
B = zeros(20*(N-1),20*(N-1));
K = 10;
for k = 1:K;
A(2*(k-1)*(N-1)+1,2*(k-1)*(N-1)+1:2*(k-1)*(N-1)+2) = [-(2+(k*pi*h/H)^2) 1];
A(2*(k-1)*(N-1)+N,2*(k-1)*(N-1)+N:2*(k-1)*(N-1)+N+1) = [-(2+(k*pi*h/H)^2) 1];
A(2*(k-1)*(N-1)+N,2*(k-1)*(N-1)+2) = [h/2]
for n = 1:K;
if (n~=k) && any(n+k == 1:2:K) %ismember(n+k,1:2:K)
x = sum((2 * H * h * n * k * ((-1)^(n + k) - 1)) / ((n^2 - k^2)^2 * pi^2 * xi));
A(2*(k-1)*(N-1)+N,2*(n-1)*(N-1)+2) = [x]; end
B(2*(k-1)*(N-1)+1,2*(k-1)*(N-1)+2) = [h/2];
end
end
Thanks in advance.
  2 个评论
Dyuman Joshi
Dyuman Joshi 2023-11-4
编辑:Dyuman Joshi 2023-11-4
"correct the use of if condition in the following code:"
How would we know what is the correct use?
You will need to specify more than just simply showing the code.
What is the objective here? What is supposed to be the "correct" use?
What is the expected output?
MADHVI
MADHVI 2023-11-4
Thank you for the response.
The objective is attached in the file.

请先登录,再进行评论。

回答(1 个)

prabhat kumar sharma
Hi Madhvi,
I assume that you are trying to construct matrices `A` and `B` for a finite difference method (FDM) and are having trouble with the summation part of the second equation within the `if` condition. The code provided seems to have a few issues that need to be corrected, including the placement of the `if` block and the summation logic.
1. The `if` block should be properly nested within the `for` loops.
2. The `sum` function is not being used correctly. If you're trying to compute a sum based on the condition, you should accumulate the sum manually within the loop.
3.It's not clear what the indices for `A` and `B` should be in the summation part, but I'll assume you're trying to update the `(k,n)` element based on the condition.
function [A,B] = fdm1(H,xi,a,b,N)
% H = 1; xi = 0.1;
% a= -1; b = 1; N=5;
h = (b-a)/N; h2 = h*h;
A = zeros(20*(N-1),20*(N-1));
B = zeros(20*(N-1),20*(N-1));
K = 10;
for k = 1:K
A(2*(k-1)*(N-1)+1,2*(k-1)*(N-1)+1:2*(k-1)*(N-1)+2) = [-(2+(k*pi*h/H)^2) 1];
A(2*(k-1)*(N-1)+N,2*(k-1)*(N-1)+N:2*(k-1)*(N-1)+N+1) = [-(2+(k*pi*h/H)^2) 1];
A(2*(k-1)*(N-1)+N,2*(k-1)*(N-1)+2) = h/2; % Removed brackets for scalar assignment
B(2*(k-1)*(N-1)+1,2*(k-1)*(N-1)+2) = h/2; % Moved outside of the inner loop
for n = 1:K
if (n ~= k) && any(n+k == 1:2:K) % ismember(n+k,1:2:K)
x = (2 * H * h * n * k * ((-1)^(n + k) - 1)) / ((n^2 - k^2)^2 * pi^2 * xi);
A(2*(k-1)*(N-1)+N,2*(n-1)*(N-1)+2) = x; % Corrected the assignment
end
end
end
end
I hope it helps!

标签

Community Treasure Hunt

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

Start Hunting!

Translated by