Length/Index based if else statements

I have a vector of variable length, for example
b = [0.25;0.5;0.75;1;1.5;1.75;2.0];
and based on the length of this vector, I have some specific parameter K against each element of b, x is the input and my final output is m
if x < b(1)
m = K(1);
elseif x < b(2)
m = K(2);
elseif x < b(3)
m = K(3);
elseif x < b(4)
m = K(4);
elseif x < b(5)
m = K(5);
elseif x < b(6)
m = K(6);
else
m = K(7);
end
I want to generalize my code based on the length of b. Here, the length was 7 so I had to run it manually like this for 7 elements. How can I generalize this for any length of b?

 採用された回答

Voss
Voss 2022 年 5 月 1 日
編集済み: Voss 2022 年 5 月 1 日

0 投票

idx = find(x < b,1);
if isempty(idx)
idx = numel(b);
end
m = K(idx);
The above assumes b is sorted in ascending order, as in the example. If b is not necessarily sorted, you'd have to sort it first.

3 件のコメント

Fawad Khan
Fawad Khan 2022 年 5 月 1 日
Thank you for your help. I guess this works for me. Although, I don't know why I'm getting an error when using this in MATLAB Function block in SIMULINK. It gives error "compilation of model failed while trying to resolve underspecified signal dimensions"
Joe Jones
Joe Jones 2022 年 7 月 27 日
Dear
Have you solved this problem? I met the error recently.
compilation of model failed while trying to resolve underspecified signal dimensions
Fawad Khan
Fawad Khan 2022 年 7 月 30 日
@Joe Jones I guess you have to use the "Ports and Data Manager" for that. In the editor window for MATLAB Function, click on "Edit Data" and then try to specify the type and size. That should work for you.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeNumeric Types についてさらに検索

製品

リリース

R2020a

タグ

質問済み:

2022 年 5 月 1 日

コメント済み:

2022 年 7 月 30 日

Community Treasure Hunt

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

Start Hunting!

Translated by