Filter löschen
Filter löschen

Generate a evenly spaced array based on two arrays

3 Ansichten (letzte 30 Tage)
Jamee Lin
Jamee Lin am 30 Apr. 2015
Kommentiert: Image Analyst am 1 Mai 2015
Hi,
I have one set of starting and ending points:
s_pt = [1,8,15];
e_pt = [3,12,20];
Now I would like to generate a evenly spaced array based on the corresponding starting and ending points. In this case, there would be three sets of data: (1-3, 8-12, 15-20). The answer would be like:
answer = [1,2,3,8,9,10,11,12,15,16,17,18,19,20]
Are there any functions to generate this kind of data without using for loop?
  3 Kommentare
Jamee Lin
Jamee Lin am 1 Mai 2015
Because it takes more time and occupied more memory with for loop.
Guillaume
Guillaume am 1 Mai 2015
Bearbeitet: Guillaume am 1 Mai 2015
This is actually something I submitted as a cody problem a while back.
And this is the reverse problem I also submitted.
If you want to see all the solutions you would have to submit a valid solution (of any size) in the first place and then solve any other cody problem.
Note that the best scoring cody solution is unlikely to be the most efficient one.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Stephen23
Stephen23 am 1 Mai 2015
Bearbeitet: Stephen23 am 1 Mai 2015
>> s_pt = [1,8,15];
>> e_pt = [3,12,20];
>> cell2mat(arrayfun(@(s,e)s:e, s_pt, e_pt, 'UniformOutput',false))
ans =
1 2 3 8 9 10 11 12 15 16 17 18 19 20
Although using a loop is likely to be faster...
  1 Kommentar
Jamee Lin
Jamee Lin am 1 Mai 2015
Thanks. This works. But, yeah, in this case, for loop is faster so I'll go with a loop.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

Image Analyst
Image Analyst am 1 Mai 2015
Is this homework? It sounds like homework, so I'll just give a hint for now. Use the colon operator (look it up) or, if you want a somewhat different way, use linspace(). You're going to have to learn the colon operator VERY soon if you want to do anything in MATLAB, so start now.
Hint:
8:12 is equal to an array 8,9,10,11,12. You can literally do the assignment in one single line of code.
  6 Kommentare
Jamee Lin
Jamee Lin am 1 Mai 2015
Yes, this is what I have now. But I was thinking not to use for loop.
Image Analyst
Image Analyst am 1 Mai 2015
Like Stephen mentioned, and you noted in your comment to him, for loops are not always the slowest approach . You could even speed this up even more if you preallocated space for "out" with the zeros() function.

Melden Sie sich an, um zu kommentieren.


Jan
Jan am 1 Mai 2015

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by