I have a vector like x=[2 3 1 5],how could I generate a vector like [1 2 1 2 3 1 1 2 3 4 5]?
Mostrar comentarios más antiguos
I have a vector like x=[2 3 1 5],how could I generate a vector like [1 2 1 2 3 1 1 2 3 4 5]?
Respuesta aceptada
Más respuestas (3)
Teja Muppirala
el 17 de Sept. de 2016
x = [2 3 1 5]
y = arrayfun(@(a)1:a,x,'uniform',0)
y = cat(2,y{:})
y = 1 2 1 2 3 1 1 2 3 4 5
2 comentarios
xiyou fu
el 17 de Sept. de 2016
Walter Roberson
el 18 de Sept. de 2016
Yes, you could write a mex file to do the work.
You can calculate the size of the output as sum() of the inputs, and you can pre-allocate that, and you can have a loop to fill it in, but it is not at all clear that it would end up being more efficient than what Teja shows.
Image Analyst
el 17 de Sept. de 2016
What rule are you using to generate that output? Here are several ways:
% Define input data.
x=[2 3 1 5]
% Generate a vector [1 2 1 2 3 1 1 2 3 4 5]:
output1 = [x(3), x(1), x(3), x(1), x(2), x(3), 1:length(x), x(end)]
output2 = [x([3, 1, 3, 1, 2, 3]), 1:length(x), x(end)]
output3 = [1 2 1 2 3 1 1 2 3 4 5];
output4 = [x([3, 1, 3, 1, 2, 3]), 1:5]
I'm sure there is a near infinite number of other rules that can get you that output vector. So what is your rule?
2 comentarios
xiyou fu
el 18 de Sept. de 2016
Image Analyst
el 18 de Sept. de 2016
Tell me the rule. I don't have the Crystal Ball Toolbox yet and since you didn't share your for loop code, I don't know what you tried to do. You still haven't told me the rule even though I explicitly asked.
I gave you 4 ways to build that vector. What's wrong with them?
Andrei Bobrov
el 19 de Sept. de 2016
x = x(:);
ons = ones(sum(x),1);
ii = cumsum(x)+1;
ons(ii(1:end-1)) = ons(ii(1:end-1)) - x(1:end-1);
out = cumsum(ons);
Categorías
Más información sobre Elementary Math en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!