Concatenate matrix numbers linspace
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Hi there,
I have a matrix variable x = [0 1 2 3]
I want to generates linearly spaced vectors in between the numbers into a variable. My problem here is concatenate the numbers into p the next time n increases.
I know i should be using linspace to generate number for eg:
for i = 1:(length(x)-1)
p = linspace(x(i),x(i+1),0.5)
end
the results i want is:
p = 0 0.5 1 1.5 2 2.5 3
Hope someone can shed some light here.
1 Kommentar
Akzeptierte Antwort
Azzi Abdelmalek
am 13 Aug. 2012
Bearbeitet: Azzi Abdelmalek
am 29 Aug. 2012
try this
x = [0.25 1 1.5 2 2.4 2.6]
x=unique(sort([x x(1:length(x)-1)+diff(x)/2]) )
if you want put 2^n-1 samples between each value use this function
function y=linspace_n(x,n)
for k=1:n
x=unique(sort([x x(1:length(x)-1)+diff(x)/2]) )
end
y=x
6 Kommentare
Matt Fig
am 14 Aug. 2012
Bearbeitet: Matt Fig
am 14 Aug. 2012
Better to use one of these. First a vectorized version:
function y = linspace_n2(x,N)
% Puts N values linear interpolated between each element of x.
% Author - Matt Fig
L = length(x);
y = bsxfun(@plus,bsxfun(@times,(0:N)',diff(x)/(N+1)),x(1:L-1));
y = [reshape(y,1,(L-1)*(N+1)),x(L)];
Or one could even go with a simplistic:
function y = linspace_n3(x,N)
% Puts N values linear interpolated between each element of x.
% Author - Matt Fig
y = [];
R = (0:N);
D = diff(x)/(N+1);
for ii = 1:length(x)-1
y = [y x(ii) + R.*D(ii)];
end
y = [y x(end)];
Azzi Abdelmalek
am 29 Aug. 2012
sorry, did'nt read your comment, yes what it does is puting 2^n-1 points instead of n
Weitere Antworten (5)
Sean de Wolski
am 13 Aug. 2012
Bearbeitet: Sean de Wolski
am 13 Aug. 2012
Here is a terrible solution:
x = 0:3; %sample x
x = [x(1:end-1); x(2:end)]; %each start/end pair
nAdd = 2; %add two elements between
xnew = interp1((1:2)',x,linspace(1,2,2+nAdd)); %interpolate (2d linspace)
xnew = vertcat(reshape(xnew(1:end-1,:),[],1),x(end)) %keep non-duplicate parts
0 Kommentare
Amazing Trans
am 14 Aug. 2012
Bearbeitet: Amazing Trans
am 14 Aug. 2012
3 Kommentare
Matt Fig
am 14 Aug. 2012
Please close out this question by selecting a best answer then post a new question and link back to this one.
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements 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!