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

Dyuman Joshi
Dyuman Joshi 2023년 9월 26일
"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일

1 개 추천

for i = 1 + h 

should be

for i = 1:numel(h)

댓글 수: 3

Voss
Voss 2023년 9월 26일
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.
Carlos Perez
Carlos Perez 2023년 9월 26일
Thank you! It worked out!!
Voss
Voss 2023년 9월 26일
You're welcome! Any questions, let me know. Otherwise, please "Accept" this answer. Thanks!

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품

질문:

2023년 9월 26일

댓글:

2023년 9월 26일

Community Treasure Hunt

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

Start Hunting!

Translated by