Can you return a matrix for all elements of vector A through vector B without a loop?
Show older comments
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
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!