Generate comma separated list in single line of code?
이전 댓글 표시
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
Guillaume
2017년 6월 13일
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
2017년 6월 13일
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
2017년 6월 13일
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.
채택된 답변
추가 답변 (3개)
Wonsang You
2017년 6월 13일
Please try the following command.
subsref(repmat({'A'},1,4),struct('type','()','subs',{{':'}}))
댓글 수: 1
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
2017년 6월 13일
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
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!