Can you return a matrix for all elements of vector A through vector B without a loop?

I was trying to vectorize my code as much as possible today and when vectorizing a for-loop I encountered this issue. It just doesn't seem to make sense to me.
If I have some vector A = [10;20;30] and some vector B = [20;30;40] is there anyway call C = A:B such that C is equal to every element of A through each element of B?
For example this output is what I expected:
[10] [15]
A = [20] B = [25]
[30] [35]
C = A:B
[10, 11, 12, 13, 14, 15]
C = [20, 21, 22, 23, 24, 25]
[30, 31, 32, 33, 34, 35]
I would like to do this without a for-loop though this is easily accomplished with a one:
for n=1:3
C(n) = A(n):B(n)
end
My confusion arises because even though a for-loop does work, C=A:B is a call on two multi-element vectors yet C=A:B actually executes as C=A(1):B(1) and returns:
C = [10,11,12,13,14,15]
And without a loop the new vector n changes nothing:
n = 1:3
[10] [15]
A(n) = [20] B(n) = [25] A(n):B(n) = [10,11,12,13,14,15]
[30] [35]
If there isn't a way around looping or simply writing it out n times, could someone at least explain what I am missing and why this doesn't work the way I expect it to?
Thanks!

 Accepted Answer

Assuming the values in A and B are consistent:
n = B(1) - A(1);
C = bsxfun(@plus,A,0:n);

3 Comments

That is incredible. I have no idea what it is doing, but thank you!
A is a column vector:
10
20
30
0:n is a row vector:
0 , 1 , 2 , ... , n
The bsxfun function is simply applying the plus operation to the two inputs, A and 0:n. Since the two operands are different dimensions, bsxfun will do what is known as a "scalar expansion" in order to accomplish the operation. That is, wherever the dimensions of the operands don't match, and one of them is a 1 then it will virtually expand that dimension to match the other operand (like doing a repmat operation without actually physically performing the repmat). So for this specific example it gets the same result as the following without actually forming these two operands physically in memory:
[10 10 10 10 10 10] [0 1 2 3 4 5]
[20 20 20 20 20 20] + [0 1 2 3 4 5]
[30 30 30 30 30 30] [0 1 2 3 4 5]

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!