Optimization of matrix calculations for loop & if statements
Afficher commentaires plus anciens
Hi,
I´m fairly new to matlab (have taken one course) and I now need to make some scripts in a separate, material science, course. I have made this script below which works fine but takes a really long time. I have done what I can/know how to do.
The problem is that the values on row 1 & 100 aswell as col 1 & 100 needs values from the first/last rows/col as the 'if' statements show.
Could someone give me a few pointers on how to improve it for efficiency?
Thanks in advance!
kappa = -9e-16;
dz = 2.7e-8/100
fileID = fopen('xf0.txt','r');
formatSpec = '%f';
A = fscanf(fileID,formatSpec);
dxrow = A(1:2:end,:);
dxtran = reshape(dxrow,[100,100]);
dx = dxtran';
% Row/Col 2,2 -> 99,99 excl col 1 & 100 %
grad = zeros(100,100);
for i = 1:100
for j = 1:100
if i == 1 && j == 1
z = kappa*(0.5*(dx(end,j)/dz)^2 + 0.5*(dx(i,j+1)/dz)^2 + 0.5*(dx(i+1,j)/dz)^2 + 0.5*(dx(i,end)/dz)^2);
elseif i == 1 && j == 100
z = kappa*(0.5*(dx(end,j)/dz)^2 + 0.5*(dx(i,1)/dz)^2 + 0.5*(dx(i+1,j)/dz)^2 + 0.5*(dx(i,j-1)/dz)^2);
elseif i == 100 && j == 1
z = kappa*(0.5*(dx(i-1,j)/dz)^2 + 0.5*(dx(i,j+1)/dz)^2 + 0.5*(dx(1,j)/dz)^2 + 0.5*(dx(i,end)/dz)^2);
elseif i == 100 && j == 100
z = kappa*(0.5*(dx(i-1,j)/dz)^2 + 0.5*(dx(i,1)/dz)^2 + 0.5*(dx(1,j)/dz)^2 + 0.5*(dx(i,j-1)/dz)^2);
elseif i-1 < 1
z = kappa*(0.5*(dx(end,j)/dz)^2 + 0.5*(dx(i,j+1)/dz)^2 + 0.5*(dx(i+1,j)/dz)^2 + 0.5*(dx(i,j-1)/dz)^2);
elseif j+1 > 100
z = kappa*(0.5*(dx(i-1,j)/dz)^2 + 0.5*(dx(i,1)/dz)^2 + 0.5*(dx(i+1,j)/dz)^2 + 0.5*(dx(i,j-1)/dz)^2);
elseif i+1 > 100
z = kappa*(0.5*(dx(i-1,j)/dz)^2 + 0.5*(dx(i,j+1)/dz)^2 + 0.5*(dx(1,j)/dz)^2 + 0.5*(dx(i,j-1)/dz)^2);
elseif j-1 < 1
z = kappa*(0.5*(dx(i-1,j)/dz)^2 + 0.5*(dx(i,j+1)/dz)^2 + 0.5*(dx(i+1,j)/dz)^2 + 0.5*(dx(i,end)/dz)^2);
else
z = kappa*(0.5*(dx(i-1,j)/dz)^2 + 0.5*(dx(i,j+1)/dz)^2 + 0.5*(dx(i+1,j)/dz)^2 + 0.5*(dx(i,j-1)/dz)^2);
end
grad(i,j) = z;
end
end
2 commentaires
Dyuman Joshi
le 17 Fév 2023
If I am understanding correct, you are trying to get the values of 4 elements around the the element (i,j) and perform the calculation as per the mentioned formula?
Alexander
le 17 Fév 2023
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Solver Outputs and Iterative Display dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!