Returning values based on range of variable values

3 次查看(过去 30 天)
I'd like my code to return 1 of 3 values for a given range of values within another variable, but cannot seem to get it to work. I've tried both if statements within a for loop as well as while statements, neither of which are returning my desired result. While neither code returns any sort of error, the original variable which should hold 1 of 3 values is never defined in my workspace. Below are both of my attempts. Any help is greatly appreciated.
%For/If:
x = 0:0.01:L;
nx = numel(x);
for n = 1:nx-1
if x<=0.2
U(n,0) = 1;
elseif x == 0.2
U(n,0) = 0.5;
else x>=0.2
U(n,0) = 0;
end
end
%While:
L=1;
x = 0:0.01:L;
while x<=0.2
U(x,0) = 1
end
while x == 0.2
U(x,0) = 0
end
while x>=0.2
U(x,0) = 0
end

回答(1 个)

Chendi Lin
Chendi Lin 2021-4-9
Hi Kevin,
The index of MATLAB starts from 1. Have you tried U(x,1)?
Best,
CD

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by