简体   繁体   中英

Creating 3D array (Matlab)

I'm currently modelling ice sheet dynamics. I have a loop that calculates the surface energy balance for 8760 hours (1:tmax) and for 8 different locations (1:no_stations). That looks like the following:

tau=0.5;
albedo=0.35;
c0=-90;
c1=10;

for i=1:tmax
    for e=1:no_stations
        psi(i,e) = tau*(1-albedo)*insol(i,4)+c0+c1*temp_stations(i,e);
    end
end

The temperature data (temp_stations) is a 8760x8 array with the corresponding temperatures for the 8760 hours at the 8 locations, and insol(i,4) is an array of 8760x4 where the fourth colomn gives the evolution of the insolation with time. My question: I want to create an extra dimension, a 8760x8x61 array where c0 is not constant but varies between -140 and -80:

c0=-140:1:-80;

How do I do this? I tried some things but it doesn't seem to work out fine.

Thanks!

For such cases that demand expansion, one can bring in bsxfun and permute for a vectorized solution, like so -

parte2 = bsxfun(@plus,permute(c0,[1,3,2]),c1*temp_stations);
psi_out = bsxfun(@plus,tau*(1-albedo)*insol(:,4),parte2);

If you don't dig bsxfun or if you just want to verify the results from vectorized approach, here's the equivalent loopy code -

for i=1:tmax
    for e=1:no_stations
        for k = 1:numel(c0)
            psi(i,e,k) = tau*(1-albedo)*insol(i,4)+c0(k)+c1*temp_stations(i,e);
        end
    end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM