Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matlab local static variable

Tags:

matlab

In order to test an algorithm in different scenarios, in need to iteratively call a matlab function alg.m.

The bottleneck in alg.m is something like:

load large5Dmatrix.mat
small2Dmatrix=large5Dmatrix(:,:,i,j,k)  % i,j and k change at every call of alg.m
clear large5Dmatrix

In order to speed up my tests, i would like to have large5Dmatrix loaded only at the first call of alg.m, and valid for future calls, possibly only within the scope of alg.m

Is there a way to acheve this in matlab other then setting large5Dmatrix as global?

Can you think of a better way to work with this large matrix of constant values within alg.m?

like image 384
Gianni Avatar asked Mar 25 '26 16:03

Gianni


1 Answers

You can use persistent for static local variables:

function myfun(myargs)
    persistent large5Dmatrix
    if isempty(large5Dmatrix)
        load large5Dmatrix.mat;
    end

    small2Dmatrix=large5Dmatrix(:,:,i,j,k)  % i,j and k change at every call of alg.m
    % ... 
end

but since you're not changing large5Dmatrix, @High Performance Mark answer is better suited and has no computational implications. Unless you really, really don't want large5Dmatrix in the scope of the caller.

like image 184
Gunther Struyf Avatar answered Mar 28 '26 09:03

Gunther Struyf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!