Hi,
I have a set of n 3x3 matricies orgenized in a 3D array with dimesions 3x3xn.
I want to operate on all 3x3 matricies: I want to get a vector of determinants and a vector of trace of each 3x3 matrix.
I also want to calculate a 3x3xn array which will hold the 3x3 inverse of each matix.
I can do it using a for loop, of couse, calculating in each iteration for the ith matrix.
Is there a simpler and faster way to do it?
Thanks,
Alon

1 Kommentar

Stephen23
Stephen23 am 11 Feb. 2020
Bearbeitet: Stephen23 am 11 Feb. 2020
"Is there a simpler and faster way to do it?"
Calculating the matrix inverse is rarely required or nor efficient when doing numeric computing. Read this to know why:
If you are really interested in efficiency, then use better tools than inv, just as the documentation recommends.
The determinant also tends to be overused by beginners who do not realize how useless it is in numeric computing. Search this forum to know why the determinant is essentially useless in numeric computing.

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Bhaskar R
Bhaskar R am 11 Feb. 2020

0 Stimmen

data = randi([1,10], 3,3,4); % your matrix with n = 4
data_det = arrayfun(@(i)det(data(:,:,i)), 1:size(data,3));
data_trace = arrayfun(@(i)trace(data(:,:,i)), 1:size(data,3));
data_inv = arrayfun(@(i)inv(data(:,:,i)), 1:size(data,3), 'UniformOutput', false);

6 Kommentare

Alon Rozen
Alon Rozen am 11 Feb. 2020
Thanks Bhaskar R :)
This looks like what I need.
A question: is there a way to create one function that will calculate all the calculation and then use 'arrayfun' only once with this function? For better performance.
Thanks,
Alon
Bhaskar R
Bhaskar R am 11 Feb. 2020
Each arrayfun using different function so you can create a function using three those statements and get output as one variable with det, trace and inv calcuations
Stephen23
Stephen23 am 11 Feb. 2020
"For better performance" use a loop.
Alon Rozen
Alon Rozen am 11 Feb. 2020
Bearbeitet: Alon Rozen am 11 Feb. 2020
I tried both - one with a loop and one with these arrayfun.
Indeed a loop works faster! You are right Stepen. Why is that? If I will use only one fuction that returns all calculation results, it also will be slower then a loop?
(Still learning how to do that)
Alon
Stephen23
Stephen23 am 11 Feb. 2020
"Why is that?"
Essentially because repeatedly calling a function handle that runs sme code is slower than just calling that code directly.
"If I will use only one fuction that returns all calculation results, it also will be slower then a loop?"
Probably... try it and find out.
Alon Rozen
Alon Rozen am 11 Feb. 2020
Thanks Stepen!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Produkte

Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by