Inverse a cell of matrices
3 views (last 30 days)
Show older comments
The MVP Walter was great and helped me created a cell of matrices but I ran into the problem the I will need to find the inverse matrices of each matrix. My code is:
T1_theta = [-90:5:90];
M = sind(T1_theta);
N = cosd(T1_theta);
T1 = arrayfun(@(m,n)[m^2 n^2 0 0 0 2*m*n;
n^2 m^2 0 0 0 -2*m*n;
0 0 1 0 0 0;
0 0 0 m -n 0;
0 0 0 n m 0;
-m*n m*n 0 0 0 m^2-n^2], M, N, 'uniform', 0);
This code produces a 1x37 cell comprised of 6x6 matrices. I thought that the code:
inv(T1)
would work but I understand why it doesnt. I was thinking of possibly doing another "arrayfun" function over top of the cell if that is possible?
0 Comments
Answers (2)
James Tursa
on 24 Feb 2021
Edited: James Tursa
on 24 Feb 2021
Yes, you can do something like this:
T1inv = cellfun(@inv,T1,'uni',false);
That being said, this begs the question of what you will be doing with this downstream in your code, and if maybe there isn't a better formulation for your overall problem that uses backslash instead. How will you be using the T1 inverses downstream in your code?
0 Comments
Walter Roberson
on 24 Feb 2021
T1inv = cellfun(@inv, T1, 'uniform', 0);
However, most of the time you should avoid using inv() . It is not common that you need the inverse of a matrix in its own right: you normally need to multiply the inverse by another matrix. In such situations you should replace inv(A)*B with A\B and you should replace B*inv(A) with B/A
For example if you were planning to do T1inv{1}*B with constant B, then instead of forming T1inv do
T1invB = cellfun(@(A)A\B, T1, 'uniform', 0);
2 Comments
Walter Roberson
on 24 Feb 2021
C_bar = cellfun(@(t1, t2) t1\C*t2, T1, T2, 'uniform', 0);
col1mat = cell2mat(cellfun(@(c) c(:,1), C_bar(:).', 'uniform', 0));
The C_bar(:).' is an idiom for ensuring that C_bar is a row vector of cells instead of potentially being a column vector of cells. There is no "reshape to row vector" operator, but there is a "reshape to column vector" operator and a transpose operator, so (:).' forces column and makes it row afterwards. You can remove the (:).' if you are sure that C_bar will be a row vector of cells.
See Also
Categories
Find more on Resizing and Reshaping Matrices 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!