How do you create an array around a central value?

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]

 채택된 답변

Star Strider
Star Strider 2015년 4월 6일
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

PR
PR 2015년 4월 6일
Thanks for your reply.
I would like the center point and resolution to be arguments and the number of points to always be 5 (hence the constant declaration).
Is there a for loop way that could be easier for me to grasp?
My pleasure.
If you always only want 5 points, my anonymous function becomes:
generate_array = @(CtrPt,Res) linspace(CtrPt-Res*2, CtrPt+Res*2, 5);
The linspace function is about as efficient as it is possible to get, and has been a part of MATLAB as long as I can remember. You could probably do this with a loop, but a simple colon-operator vector would seem to do as well, at least in the current application, although I cannot guarantee how robust it would be for other situations:
generate_array = @(CtrPt,Res) [CtrPt-Res*2 : Res : CtrPt+Res*2];
(The square brackets aren’t strictly necessary, but it improves the readability of the code. I know by looking at it that it is an array.)
I still prefer (and recommend) to use linspace because of its flexibility.
PR
PR 2015년 4월 6일
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
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

질문:

PR
2015년 4월 6일

댓글:

2015년 4월 6일

Community Treasure Hunt

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

Start Hunting!

Translated by