Fast ways to generate multiple sequences without using for loop
Mostrar comentarios más antiguos
Hi all,
Suppose, I have two arrays:
startIds = [x1, x2, x3]
endIds = [y1, y2, y3]
The two arrays have the same length and can be long. We may assume that (endIds(ii)-startIds(ii)) are the same for all positions ii. Is there any fast ways to generate multiple sequences without using for loop?
startIds(1):endIds(1)
startIds(2):endIds(2)
startIds(3):endIds(3)
Thanks!
-Thang
Respuesta aceptada
Más respuestas (1)
Geoff Hayes
el 18 de Mayo de 2015
For example, if we assume (as you have stated) that (endIds(ii)-startIds(ii)) are identical for all ii then
startIds = [1 2 3];
endIds = [12 13 14];
cell2mat(arrayfun(@(x)startIds(x):endIs(x),1:length(startIds), 'UniformOutput',false)')
would produce the following
1 2 3 4 5 6 7 8 9 10 11 12
2 3 4 5 6 7 8 9 10 11 12 13
3 4 5 6 7 8 9 10 11 12 13 14
We arrayfun to a apply the anonymous function
@(x)startIds(x):endIds(x)
to each of the pairs in startIds and endIds (much like your for loop would do). We then transpose this result (which becomes a 3x1 cell array of 1x12 elements each) and convert it to a matrix using cell2mat.
Try the above and see what happens!
3 comentarios
Thang Luong
el 18 de Mayo de 2015
Walter Roberson
el 18 de Mayo de 2015
You didn't ask about fast ways to do it: you asked about doing it without a for loop.
Thang Luong
el 18 de Mayo de 2015
Categorías
Más información sobre 2-D and 3-D Plots 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!