Modify Matrix / multidimensional array with Colon in Colon
Afficher commentaires plus anciens
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 commentaires
"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
le 4 Août 2023
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Get Started with MATLAB dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!