Single-precision unit-spaced vector without conversion from double

1 次查看(过去 30 天)
Hi,
is there a fast way to create a unit-spaced vector (m:n) as single precision, and avoid conversion from double?
I want to avoid out-of-memory related errors. The following method may fail (with a "Conversion to single from double is not possible." error) if k is very large.
m = 0;
n = 10;
k=n-m+1;
x = zeros(k,1,'single');
x(1:k) = m:n;
I guess, it is not different, or perhaps even worse (double both for the vector AND for the index) than doing simply
x = single(m:n);
I'd like to generate each element of m:n already as single precision. One approach that comes to my mind is to divide the vector into parts and fill each part by conversion from a smaller double vector.
Is there any better method?
Thanks!

采纳的回答

Steven Lord
Steven Lord 2020-1-21
Don't create the vector as a double array then convert the vector to single.
Convert the scalar values from double to single then build the vector by calling the colon operator : on the single scalars.
a = 0;
b = 1e5;
x = single(a:b);
as = single(a);
bs = single(b);
xs = as:bs;
  2 个评论
Robert Borkowski
Robert Borkowski 2020-1-21
编辑:Robert Borkowski 2020-1-21
Great answer, thank you!
Do you know if
x1=a:bs
or
x2=as:b
implicitly converts the double operand into single BEFORE the vector is created, i.e., it's equivalent to your proposed as:bs syntax?
Steven Lord
Steven Lord 2020-1-21
You can see more information about specifically which function would get called with certain inputs if you call the which function. See the "Locate Function Invoked with Given Input Arguments" example on the documentation page for the which function or just look below. With a, as, b, and bs as defined above in the workspace:
>> which -all colon(a, bs)
built-in (C:\Program Files\MATLAB\R2019b\toolbox\matlab\ops\@single\colon) % single method
>> which -all colon(as, bs)
built-in (C:\Program Files\MATLAB\R2019b\toolbox\matlab\ops\@single\colon) % single method
>> which -all colon(a, b)
built-in (C:\Program Files\MATLAB\R2019b\toolbox\matlab\ops\@double\colon) % double method
In the first two cases, MATLAB "knows" it needs to create a single vector while in the latter it creates a double vector.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by