Calculate C = A \ B{i} for each cell in B when B is a cell array?

4 views (last 30 days)
I have code segment that’s slowing my script down which I suspect should be possible to vectorize or speed up in some way. I want to use mldivide and calculate:
C = A \ B;
Where A is 27x27 matrix and B is a cell array with 1000 cells where each cell has size (27 x 6588) .
I want to do the calculation for each cell in B with the same A that never changes. At the moment I’m doing this in a loop like this:
for i=1:length(B)
C = A \ B{i}; %doing the calculation on one cell in B
%Doing things with C here
end %moving on to the next one
But this means doing the calculation a thousand times in a loop. Isn’t there any quicker way of calculating C for all cells in B outside of the loop? I suspect cellfun could be a function that is suitable for something like this but I haven’t figured out how to get it to work.
Any suggestions on how to calculate this without the loop?

Accepted Answer

John D'Errico
John D'Errico on 12 Aug 2015
Edited: John D'Errico on 12 Aug 2015
Time for linear algebra 101. Factor A, using either a QR or LU or cholesky decomposition as appropriate, or pinv. The exact form depends on what you know about A.
Then the solution is no more than a VERY fast computation for each cell.
And, no, cellfun is NOT the right solution, IF you are trying to use backslash directly. That will still force the code to repeatedly factorize A. You need to factor A IN ADVANCE. THEN you could use cellfun.
For example, the simplest approach is to compute
Ap = pinv(A);
Then it is merely a matrix multiply of Ap with every cell. THAT you can do using cellfun.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!