Split vector by value ranges?

16 ビュー (過去 30 日間)
Don Kelly
Don Kelly 2021 年 1 月 26 日
編集済み: Don Kelly 2021 年 1 月 28 日
Given:
w=[2,8,3,30,4,50,100,200,4,80,500]
How can I turn the following into a single line of code?
r=w(w>0 & w<10)
s=w(w>10 & w<100)
t=w(w>100 & w<1000)
I tried variations of:
[r,s,t]=w(w>0 & w<10),w(w>10 & w<100),w(w>100 & w<1000)
  2 件のコメント
Stephen23
Stephen23 2021 年 1 月 26 日
編集済み: Stephen23 2021 年 1 月 26 日
@Don Kelly: I removed all of those ```and ´´´ characters, and formatted your code correctly by simply selecting the text and clicking the CODE button.
Don Kelly
Don Kelly 2021 年 1 月 28 日
編集済み: Don Kelly 2021 年 1 月 28 日

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

採用された回答

weikang zhao
weikang zhao 2021 年 1 月 26 日
Use anonymous functions, it allows you to implement quite complex functions in one line. MATLAB supports dot indexing into function call results, as in foo(arg).prop. Other forms of indexing into function call results (with parentheses such as foo(arg)(2) or with curly braces such as foo(arg){2}) are not supported. So, I used feval and anonymous functions to complete this function in disguise.
w=[2,8,3,30,4,50,100,200,4,80,500];
[r,s,t]=feval(@(x) x{:},arrayfun(@(a,b) w(w>a&w<b),[0,10,100],[10,100,1000],'UniformOutput',false));
have fun!
  3 件のコメント
Don Kelly
Don Kelly 2021 年 1 月 26 日
I guess also is there a less advanced way?
weikang zhao
weikang zhao 2021 年 1 月 26 日
An anonymous function does not need to name the function handle, you can destroy it in place after using it like I did. You can view the output of arrayfun&`feval`, this will help you understand. `arrayfun` can apply function to each element of array, so
arrayfun(@(a,b) w(w>a&w<b),[0,10,100],[10,100,1000],'UniformOutput',false)
will get a cell array and three matrices are stored separately.

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

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2021 年 1 月 26 日
[r,s,t] = deal(w(w>0 & w<10),w(w>10 & w<100),w(w>100 & w<1000))
  1 件のコメント
Don Kelly
Don Kelly 2021 年 1 月 28 日
Thank you Walter,
I accepted weikang zhao's answer since it was functional and first. I wanted to say that I am really grateful for your answer as well.

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

カテゴリ

Help Center および File ExchangeNumerical Integration and Differential Equations についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by