Run array into Looped Function File

Need help with the following code. I can run if the input value (h1) is a single value but not an array.
home;clear;clf;close
%% Define Constants
H = 7; % Height of the Tank [m]
R = 2; % Raduis of the Tank [m]
h1 = linspace(0,2); % Liquid Height range 1 [m]
h2 = linspace(0,7); % Liquid Height range 2 [m]
%% Calculate Volume By Calling Function File
V1_analytical = Tank_volume(h1,H,R);
V2_analytical = Tank_volume(h2,H,R);
%% Plot Results
plot(V1_analytical,h1)
%% Function File
function V= Tank_volume(h,H,R)
if h < 0
error('Height cannot be less than 0');
elseif h < R
V = 2*pi * R ^ 3 / 3;
elseif h >= R && h<H
V = (pi*h^2/3)*(3*R-h);
else
error('it is bad to spill product on the floor!');
end
end
I keep gettint this error
Array indices must be positive integers or logical values.
Error in Quiz2>Tank_volume (line 18)
if h(i) < 0
Error in Quiz2 (line 11)
V1_analytical = Tank_volume(h1,H,R);

1 个评论

"I can run if the input value (h1) is a single value but not an array."
Yes, because your code is not equipped for that.
Also, how do you plan to plot the error messages that occur for a range of values?

请先登录,再进行评论。

回答(1 个)

Voss
Voss 2023-9-26
for i = 1 + h 

should be

for i = 1:numel(h)

3 个评论

Now the code in the question has been edited and the line reported in the error no longer exists in the code, so I don't know what the situation is.
Thank you! It worked out!!
You're welcome! Any questions, let me know. Otherwise, please "Accept" this answer. Thanks!

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品

评论:

2023-9-26

Community Treasure Hunt

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

Start Hunting!

Translated by