How to associate a range of values to a certain vector component in a if statement?

1 view (last 30 days)
My current code looks like this:
if x(38)>=0 && x(38)<1
clalfaw_sec1 = clalfaw1;
elseif x(38)>=1 && x(38)<2
clalfaw_sec1 = clalfaw2;
elseif x(38)>=2 && x(38)<3
clalfaw_sec1 = clalfaw3;
elseif x(38)>=3 && x(38)<4
clalfaw_sec1 = clalfaw4;
elseif x(38)>=4 && x(38)<5
clalfaw_sec1 = clalfaw5;
end
So I wanted to clean it up so I could add variables more easily. Clalfaw is currently written as single variables, so I thought about writing it as a vector instead, and make the if cycle through it, as x(38) is on a certain range of values. But I couldn't think of any way that doesn't ends up similar to the original code. Could someone give a tip?

Accepted Answer

Dyuman Joshi
Dyuman Joshi on 20 Jan 2023
You can put all the clalfaws in a single array and using indexing -
arr=[clalfaw1 clalfaw2 clalfaw3 clalfaw4 clalfaw5];
idx=floor(x(38))+1;
clalfaw_sec1=arr(idx)

More Answers (0)

Categories

Find more on Function Creation in Help Center and File Exchange

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!