user2305193
user2305193

Reputation: 2059

how to use bsxfun with linspace [1 5] -> [1 2 3 5 6 7]

In matlab I'm attempting to get from a vector

start=[1 5 10]

to a solution looking like this, adding [1:3] to every value, expanding the vector:

sol=[1 2 3 5 6 7 10 11 12]

I tried

fun=@(a,b) a-b:a;
test=3
bsxfun(fun,start,test)

but it only works for the first value (start(1)). How can I turn the variable start into something like the solution vector?

Related answer I couldn't make work

Upvotes: 2

Views: 141

Answers (1)

Suever
Suever

Reputation: 65430

This is because the first and second inputs to the function provided to bsxfun aren't necessarily scalars.

In your example, the array [1, 5, 10] is being passed as the first input to your anonymous function and colon ignores all but the first element if the first input is an array

colon([1 5 10], 3)
%   1   2   3

To accomplish what you're trying to do, you can just add 0:2 to each element of start using @plus and reshape the result to be a row vector.

reshape(bsxfun(@plus, start, (0:2).'), 1, [])

What this actually does is adds [0, 1, 2] to each element of start

bsxfun(@plus, start, (0:2).')
% 1     5    10
% 2     6    11
% 3     7    12

And then we reshape this into a row vector. Since MATLAB uses column-major ordering, the reshaped data will go down the columns and yield the expected result.

Or if you're on R2016b or newer

reshape(start + (0:2).', 1, [])

Upvotes: 4

Related Questions