Using colon operator to create evenly spaced vectors for individual elements of arrays simply and without looping

Is there any way (other than using looping) to perform an element-by-element operation on two matrices such that a vector is created with equal spacing between the corresponding elements of each matrix? For example, if I had two matrices:
A=[1,2,3; 4,5,6] B=[12,13,14; 15,16,17]
It there a simple way to create an array (perhaps a cell or multidimensional array) that holds A(1,1):B(1,1), A(1,2):B(1,2) and so on, without manually typing all of this?
Apologies in advance if the question is unclear or the answer is obvious--I have minimal matlab experience and have run into a mental block trying to get this to work.

 Accepted Answer

A=[1,2,3; 4,5,6];
B=[12,13,14; 15,16,17]
C = cellfun(@(x,y)x:y,num2cell(A),num2cell(B),'uni',false)
No guarantees it'll be faster than a for-loop though. The conversions using num2cell() aren't known for their speed.

2 Comments

Thanks! I'll give it a try. It actually works out, as the situation in which I'll be applying this involves cell arrays already. Apologies--I probably should have mentioned that rather than just going for simplicity in my example. =P

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!