Loop inside a loop isn't working
5 views (last 30 days)
Show older comments
I am trying to create a hemisphere. But I seems like the loop inside the loop isn't working. Has somebody an idea what might be the problem?
% the values of the adjacent site
x =[-1:0.001:1];
%creating a template where I can fill in the values later on
y=zeros(2000, 2000);
% creating the highest arc (ARC A) of a hemisphere
j=0
for i=x
j=j+1;
y(j, 1000)=sqrt(1-(i^2));
end
%%
% filling in the other values, creating arcs based on the values of ARC A
for w=1:2000
H=y(w,1000) ;
L=round(H*1000);
r=1000-L;
L2=L/1000;
for xmod=-L2:0.001:L2
y(r,w)=sqrt(H^2-(xmod)^2);
r=r+1;
end
end
% plotting the matrix
surfl(y)
shading interp
I have also attached a sketch of my idea so you can imagine it better.
0 Comments
Accepted Answer
Dyuman Joshi
on 12 Nov 2023
Edited: Dyuman Joshi
on 12 Nov 2023
There are 2001 elements in x, not 2000. (Imo) It's better to use numel() to get the number of elements, rather than manually using a value.
% the values of the adjacent site
%% Square brackets are super-fluous here
x = -1:0.001:1;
n = numel(x)
%creating a template where I can fill in the values later on
y=zeros(n);
%% Vectorized
y(:,1000) = sqrt(1-x.^2); % creating the highest arc (ARC A) of a hemisphere
% filling in the other values, creating arcs based on the values of ARC A
for w=1:n
H=y(w,1000);
L=round(H*1000);
%% Correction, as H ranges from [0 1], L range from [0 1000]
%% Thus, 1000-L would be 0 when L=1000, which can not be used as an index in MATLAB
r = 1001-L;
L2 = L/1000;
xmod = -L2:0.001:L2;
%% Vectorized
y(r+(0:numel(xmod)-1), w) = abs(sqrt(H^2-xmod.^2));
end
% plotting the matrix
surfl(y)
shading interp
2 Comments
Dyuman Joshi
on 13 Nov 2023
You are welcome!
Yes, Vectorization improves the code by many factors!
"I am wondering whether it is possible to create a ball so you have 2 z-values for each xy-value."
Do you mean like this -
x = -1:0.001:1;
n = numel(x);
y=zeros(n);
y(:,1000) = sqrt(1-x.^2);
for w=1:n
H=y(w,1000);
L=round(H*1000);
r = 1001-L;
L2 = L/1000;
xmod = -L2:0.001:L2;
y(r+(0:numel(xmod)-1), w) = abs(sqrt(H^2-xmod.^2));
end
%% Plot half-sphere
surfl(y)
hold on
%% Plot the other half, using the negative of the values
surfl(-y)
shading interp
More Answers (1)
Steven Lord
on 13 Nov 2023
[X, Y, Z] = sphere;
figure
surf(X, Y, Z)
title("Full sphere")
axis square
limits = axis(gca);
figure
% Chop off the bottom half of the sphere, leaving a copy of Z unchanged so
% you can compare the two arrays Z and Z2
Z2 = Z;
Z2(Z < 0) = NaN;
surf(X, Y, Z2)
title("Half sphere")
axis equal
axis(limits)
0 Comments
See Also
Categories
Find more on Surface and Mesh Plots 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!