I have a big matrix, 3x3x151.
I was struggling to write a code to find the inverse of each 3x3 matrix and save it in a new matrix.
tried a for loop approach but got no where
CodePudding user response:
This is precisely what pageinv
was designed for. If you have R2022a or later, simply:
x = rand(3, 3, 151);
y = pageinv(x);
As the comments above point out, and as is fairly well known, the matrix inverse itself often isn't what you want. There's also pagemldivide
if that's what you really want to do.
CodePudding user response:
a quick solution is to split the matrix into cell arrays of 3x3 matrices, and then call cellfun
, try this
a=rand(3,3,151);
b=squeeze(num2cell(a,[1,2]));
c=cellfun(@inv, b, 'UniformOutput', false) % inversions of 3x3 matrices
if you want to assemble those back to a matrix, you can call
cmat=reshape(cell2mat(cellfun(@(x) x(:), c', 'UniformOutput', false)), size(a))