Can you extract an element from an array in the same line as you create the array?
显示 更早的评论
Hi,
I am wondering if it possible to extract data from an array in the same line as the array is created. The purpose is to remove the need for a separate line of code in which the data is extracted.
Example of separate array creation and data extraction:
s = "hello world";
t = split(s, " "); % In this line the array "t" is created
t(1) % In this line the first element of "t" is extracted
>> ans =
"hello"
My question: Can lines 2 and 3 be combined? Something like this:
t = split(s, " ")(1)
>> ans =
"hello"
Thanks in advance,
Jack
采纳的回答
更多回答(1 个)
madhan ravi
2019-5-16
Why not?
regexp(s,'\w*','match','once')
3 个评论
madhan ravi
2019-5-16
Perhaps all you need is:
subsref(split(s," "),substruct('{}',{1}))
Jack Warren
2019-5-17
编辑:Jack Warren
2019-5-17
subsref will always work (as long as you've constructed the arguments properly). My point was that using it for the sake of saving one line is not a good idea as it makes the code more obscure. I would always favour clarity over conciseness. It is often said that code is Write Once Read Many, so you should concentrate on making the code easier to read even if it takes longer to write.
类别
在 帮助中心 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!