Senyokbalgul
Senyokbalgul

Reputation: 1102

Matlab: how to make [1 3 5] become [1 nan 3 nan 5]

If there is an array called numbers shown below. How can I transform this array so that numbers becomes realNumbers as shown below where any number from 1:10 that does not exist in numbers is filled with a nan. realNumbers is what I want as the result and doesn't exist before the computation and only numbers exists. This is in Matlab code.

numbers = [1 3 5 6 10];
realNumbers = [1 nan 3 nan 5 6 nan nan nan 10];

Upvotes: 3

Views: 120

Answers (3)

Tasos Papastylianou
Tasos Papastylianou

Reputation: 22225

You already have answers for when the numbers are integers. Your question, however, specifically asks for real numbers in general, so I will give a more general solution.

>> Numbers = [0.5, 2, 3.5]
Numbers =
   0.5  2.0  3.5
>> RealNumbers = [0:0.5:5]
RealNumbers =
   0.0  0.5  1.0  1.5  2.0  2.5  3.0  3.5  4.0  4.5  5.0
>> Members = ismember (RealNumbers, Numbers)
Members =
   0    1    0    0    1    0    0    1    0    0    0
>> RealNumbers(~Members) = nan
RealNumbers =
   NaN  0.5  NaN  NaN  2.0  NaN  NaN  3.5  NaN  NaN  NaN

Upvotes: 3

Luis Mendo
Luis Mendo

Reputation: 112689

Another way, using the very versatile accumarray function:

numbers = [1 3 5 6 10];
realNumbers = accumarray(numbers(:), numbers(:), [], @(x)x(1), NaN).';

Upvotes: 6

Shai
Shai

Reputation: 114816

realNumbers = nan(1,10);
realNumbers(numbers) = numbers

Upvotes: 4

Related Questions