Effacer les filtres
Effacer les filtres

How can I create a cell array whose elements reflect a length based on a given input vector?

1 vue (au cours des 30 derniers jours)
For example, I want to repeat the character 'b' a specified number of times based on a vector; let's say the vector is [3 2 4]. My desired output would be a 1x3 cell array with elements:
{'bbb'} {'bb'} {'bbbb'}
Ideally, I'd like to implement this without a loop. I'm sure there's some nifty Matlab function that accomplishes this, but I haven't been able to find it. repmat and repelem don't appear to be relevant for this particular application (unless I'm using them incorrectly).
Thank you.
  1 commentaire
KALYAN ACHARJYA
KALYAN ACHARJYA le 4 Mai 2019
Members, how can avoid this for loop?
in=[3 2 4];
result={};
for i=1:length(in)
result{i}=repmat('b',1,in(i));
end

Connectez-vous pour commenter.

Réponse acceptée

Stephen23
Stephen23 le 4 Mai 2019
In one line:
>> V = [3,2,4];
>> S = 'b';
>> C = mat2cell(repmat(S,1,sum(V)),1,V);
>> C{:}
ans = bbb
ans = bb
ans = bbbb
  1 commentaire
Dwight Schrute III
Dwight Schrute III le 4 Mai 2019
Nimble utilization of mat2cell functionality. This works perfectly; I wish I had thought of it. Thanks for your answer, Stephen.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Multidimensional Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by