How do you create an array around a central value?

4 visualizaciones (últimos 30 días)
PR
PR el 6 de Abr. de 2015
Comentada: Star Strider el 6 de Abr. de 2015
I would like to write a function such as:
function [ array ] = generate_array( center_pt, resolution )
NB_POINTS = 5;
(...)
end
so that calling [ array ] = generate_array( 5, 2.5 )
array = [0 2.5 5 7.5 10]

Respuesta aceptada

Star Strider
Star Strider el 6 de Abr. de 2015
How about this? It has three arguments, since I don’t know if you want the number of points to be an argument or decided by the function.
NrPts = 5;
CtrPt = 5;
Res = 2.5;
generate_array = @(CtrPt,NrPts,Res) linspace(CtrPt-Res*fix(NrPts/2), CtrPt+Res*fix(NrPts/2), NrPts);
It generates the array you specified, and seems to be robust for other argument values.
  4 comentarios
PR
PR el 6 de Abr. de 2015
Wow, ok! I can see now that linspace is the path of least resistance.
Everything remains contained in one line of code.
I have learned a great deal from your reply.
Many thanks
Star Strider
Star Strider el 6 de Abr. de 2015
My pleasure! I very much appreciate your compliment.
In Answers, we (collectively) strive to post the most efficient and fastest code, assuming that is what the person who posts the Question wants. Most of us also provide links to the relevant documentation, as well as a brief explanation of how the code we post works, using comments on each line or a short narrative description.
Also, if my Answer solved your problem, please Accept it.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by