Linearly spaced vectors
Show older comments
For academic interest, I wish to further improve the speed and memory performance of the included code. The function's purpose, which I've provided below, is to generate a series of linearly spaced vectors using only an input vector for defining the upper and lower limits.
EXAMPLE:
x = [0
12.872
21.453
30.132
40.371
57.631
77.816
100];
increment = 2
y = f(x,increment)
An important aspect to note is that, with the exception of edge conditions, the generated outputs are even and monotonically increasing:
y = [0, ..., 12, 12.872,
12.872, 14, ..., 20, 21.453,
21.453, 22, ..., 30, 30.132,
...
57.631, 58, ..., 76, 77.816,
77.816, 78, ..., 100];
The method currently being used is as follows:
function y = multi_linspace(x,increment)
% Multi_linspace generates a vector of linearily spaced vectors.
input_length = length(x);
fractional = @(x)([fix(x)*Inf^(x-fix(x)),x]);
for i=1:input_length
if (i ~= input_length)
buffer{i}=ceil(x(i))+mod(ceil(x(i)),2):increment:x(i+1);
edge(1,:)=fractional(x(i));
edge(2,:)=fractional(x(i+1));
id = isinf(edge(:,1));
prefix = id(1); suffix = id(2);
if prefix
% x(i) == edge(1,2)
buffer{i} = [x(i),buffer{i}];
end
if suffix
% x(i+1) == edge(2,2)
buffer{i} = [buffer{i},x(i+1)];
end
end
end
y=[buffer{:}]';
end
Accepted Answer
More Answers (3)
the cyclist
on 2 Mar 2011
I made no attempt to understand the complexity of your code, but I did check that the following reproduces your result exactly, for the test case you gave.
I don't know if it's faster, but it is shorter and simpler. But maybe you are testing special cases, which I am not.
function y = multi_linspace2(x,increment)
y = (x(1):increment:x(end))';
for ii=2:length(x)-1
y = [y(y<x(ii)); x(ii); x(ii); y(y>=x(ii))];
end
end
1 Comment
Ragaar Ashnod
on 2 Mar 2011
Sean de Wolski
on 2 Mar 2011
x2 = [x(1:end-1), x(2:end)]
x2 = num2cell(x2,2)
y = cellfun(@(x)x(1):increment:x(2),x2,'uni',false)
%Scd
2 Comments
Ragaar Ashnod
on 2 Mar 2011
Sean de Wolski
on 2 Mar 2011
Just change the function handle:
y = cellfun(@(x)[x(1), ceil(x(1)):increment:floor(x(2)), x(2)],x2,'uni',false)
Categories
Find more on Programming in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!