Generate comma separated list in single line of code?
Show older comments
I would like to put a piece of code within an expression which generates a comma separated list, without having to create a dummy variable. Is this possible? I was trying to use subsref(), like this:
subsref(repmat({'A'},1,4),struct('type','{}','subs',{{':'}}))
But this only returns a single output. It seems like subsref can't actually behave like A{:} . Is there another way?
The specific reason I would like to do this is for indexing an array where the dimension is unknown prior to runtime. So instead of (for example)
idx = [{1} repmat({':'},1,ndims(inputData)-1)];
output = A(idx{:});
I could do something like
output = A(<expression>);
8 Comments
Guillaume
on 13 Jun 2017
Your stated reason and example does not seem to match the question. With you example, why can't you use subsref directly with A?
Evan
on 13 Jun 2017
The point is, why can you not simply do this?:
output = subsref(A,S);
This is, after all, how subsref works. What possible advantage do you see in diverting yourself with expression ?
Evan
on 13 Jun 2017
Don't worry about others. They will cope just fine :)
This is a relatively uncommon topic to deal with, so regarding this thread:
- beginners are unlikely to stumble across it.
- it documents particular concepts that otherwise do not get discussed much.
It matters more whether there is a clear and useful answer than whether the initial question might confuse. If it were a question where the answers just add to the confusion then it would be bad, but if the accepted answer (accepting Stephen's answer would be useful!) clears up the confusion then that is fine.
Hence, I removed the flag from the question.
Accepted Answer
More Answers (3)
Wonsang You
on 13 Jun 2017
Please try the following command.
subsref(repmat({'A'},1,4),struct('type','()','subs',{{':'}}))
1 Comment
This answer is irrelevant to the topic at hand: it does not return a comma-separated list as the original question asks about, and even the title clearly states: "Generate comma separated list.."
This code simply returns a cell array, and is equivalent to (:).
The original question asks about generating a comma-separated list, equivalent to {:}.
Someone apparently does not know the difference, and voted for it. Perhaps they liked the pretty output.
Walter Roberson
on 13 Jun 2017
Expand = @(cell) cell{:};
Expand(repmat({'A'},1,4))
A one-line approach that has been possible since R2019b:
struct('x',{'A','B','C','D'}).x
Categories
Find more on Operations on Strings in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!