Sorry, no message is displayed. But the result in not a 3d matrix where the values are computed at each node above the surface. I obtain a 1x1x11 matrix.
where is the error?
1 view (last 30 days)
Show older comments
Hi, running the following script:
% Create a data set:
x = rand(100,1)*4 - 2;
y = rand(100,1)*4 - 2;
S = x.*exp(-x.^2-y.^2) * 1000;
% Construct the interpolant:
F = TriScatteredInterp(x,y,S);
% Evaluate the interpolant at the locations [XI,YI].
XI = -2:0.25:2;
YI = -2:0.1:2;
[XImat,YImat] = meshgrid(XI,YI);
ZImat = F(XImat,YImat);
% Define a set of ZI locations
ZI = -500:100:500;
% Find the node above the surface S
BW = false(length(YI),length(XI),length(ZI));
for i = 1:length(YI)
for j = 1:length(XI)
BW(i,j,:) = ZImat(i,j)<ZI;
end
end
KImat = zeros(size(ZImat));
for i = 1:length(YI)
for j = 1:length(XI)
firstIndex = find(BW(i,j,:),1);
if ~isempty(firstIndex)
KImat(i,j) = firstIndex;
end
end
end
% Create a 3d grid where to compute a value at each node above the surface S
[X,Y,Z] = meshgrid(XI,YI,ZI);
for i = 1:length(YI)
for j = 1:length(XI)
if KImat(i,j) == 1
for i = 1:length(Y)
for j = 1:length(X)
for k = 1:length(Z)
T_geotherm(i,j,k) = 18 + 0.003 .* (Z(i,j,k));
end
end
end
end
end
end
dislay this message: 'Attempted to access Z(1,1,12); index out of bounds because size(Z)=[41,17,11].'
where is the error?
Thanks, Gianluca
4 Comments
Wayne King
on 17 Sep 2012
The variable, T_geotherm, is not being generated because your if statement if KImat(i,j) == 1 is never true
Accepted Answer
Jan
on 17 Sep 2012
Edited: Jan
on 17 Sep 2012
Matlab code gets much cleaner and easier to debug, when vectorization is applied:
Ugly and due to a missing pre-allocation slow in addition:
for i = 1:length(Y)
for j = 1:length(X)
for k = 1:length(Z)
T_geotherm(i,j,k) = 18 + 0.003 .* (Z(i,j,k));
end
end
end
Beautiful and fast:
T_geotherm = 18 + 0.003 .* Z;
Btw, using nested loops with the same counter is not really clean, but not an error:
for i = 1:length(YI)
for j = 1:length(XI)
if KImat(i,j) == 1
for i = 1:length(Y)
for j = 1:length(X)
It is strongly recommended to avoid such confusing constructions.
More Answers (1)
Wayne King
on 17 Sep 2012
I can run this without error. I think you have some variable in your workspace that is conflicting with this and causing the error.
Can I suggest you first clear the workspace and then try to run this script?
0 Comments
See Also
Categories
Find more on Interpolation 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!