Can you extract an element from an array in the same line as you create the array?

조회 수: 26 (최근 30일)
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

채택된 답변

Guillaume
Guillaume 2019년 5월 16일
No, unfortunately in matlab, you cannot index directly into the return value of a function.
You could use subsref as demonstrated by Madhan to do the indexing, however I would advise against that.Yes, subsref is the function actually called when you perfom indexing but the lack of clarity and the high chance of making a mistake don't make it worth it just so you can write one line of code instead of two.

추가 답변 (1개)

madhan ravi
madhan ravi 2019년 5월 16일
Why not?
regexp(s,'\w*','match','once')
  댓글 수: 3
Jack Warren
Jack Warren 2019년 5월 17일
편집: Jack Warren 2019년 5월 17일
Thanks for the answers. As Guillaume has suggested substrct may not work reliably, so I will trial it with caution.
Guillaume
Guillaume 2019년 5월 17일
편집: Guillaume 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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

제품


릴리스

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by