Modify Matrix / multidimensional array with Colon in Colon
Show older comments
In Matlab I can modify an array with a colon like this:
n = 90;
A = zeros(n,1);
A(1:n) = (1:n).^2;
If I have a two dimensional array, a matrix it gets more complicated but it is still easy to modify all entities with a loop:
n2 = 10;
A = zeros(n,n2);
for index = 1:n2
A(1:n,index) = (index:index+n-1).';
end
or
n2 = 10;
A = zeros(n,n2);
for index = 1:n2
A(1:n,index) = colon(index, index+n-1).';
end
I would like to use a direkt matrix calculation instead of a for loop to increase my speed, since my problem is bigger and I have to do it often.
My approach was:
A(1:n,1:n2) = colon(1:n2, (1:n2)+n-1).';
or
A(1:n,1:n2) = colon(1:n, (1:n)+n2-1);
Matlab also uses "n" and "n2" on the left side, giving me the 90-by-10 size. However, on the right side I only have a 90-by-1 or 1-by-10 size.
My current solution is unfortunately not the colon. I need to use the arrayfun and convert the resulting cell array into a matrix.
A2 = arrayfun(@(a) a:a+n-1, 1:n2, 'UniformOutput', false).';
A = cell2mat(A2).';
In Python I would use nested foor loops and be able to make this multidimensional in a singel line.
My working alternative in Matlab is significantly more computationally expensive and for more dimensions I would have to create a loop or a function that calls itself.
Isn't that somehow easier with "colon"?
2 Comments
"Isn't that somehow easier with "colon""
I doubt it.
n = 90;
n2 = 10;
A2 = arrayfun(@(a) a:a+n-1, 1:n2, 'UniformOutput', false).';
A = cell2mat(A2).'
Two efficient MATLAB approaches:
B = (0:n2-1) + (1:n).'
C = hankel(1:n,n:n+n2-1)
isequal(A,B,C)
The trick to using MATLAB effectively is to not reinvent the wheel: for many common operations there are simple functions or operations that can be used on entire arrays:
"Isn't that somehow easier with "colon""
You seem to be trying to hide a loop inside COLON: it does not work like that.
Julian
on 4 Aug 2023
Accepted Answer
More Answers (0)
Categories
Find more on Creating and Concatenating Matrices 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!