Reputation: 73
I am trying to create a set of 320 matrices, each having dimensions 1152 x 241. Each matrix represents a different time step. I am trying to populate each cell, using a random value from another file. This other file is also dimensioned 1152 x 241, but there are ~2520 time steps from which to choose.
So what is supposed to happen is pick a cell, populate with a value from a random time step from the big file, and move onto the adjacent cell and do the same thing. Repeat until 320 matrices have been created.
Problem is I run the code and I only create one matrix. What do I need to do to fix my code so that 320 matrices are created? Thanks!
clear all;
clc;
% Load datafile
load 1979_1999_tropics_subset_3mmhr.mat
% Create empty maps
rain_fake_timeseries = zeros(1152,241,320);
for i = 1:1152; % set longitude
%disp(i)
for j = 1:241; % set latitude
%disp(j)
%for k = 1:320; % create map
%disp(k)
rain_fake_timeseries = datasample(rain_sample_1979_1999,1,3);
%disp(rain_fake_timeseries)
%save random_clus_fake_timeseries.mat rain_fake_timeseries -v7.3;
%end
end
end
save random_clus_fake_timeseries.mat rain_fake_timeseries -v7.3;
Upvotes: 0
Views: 216
Reputation: 104464
This is because you are not properly indexing into your time series array to store the data. What you are doing is that you are only saving the last randomly chosen slice in your time series array. If you look at your loop closely, you are simply overwriting the output array at each iteration of the for
loop.
You are also not creating your for
loop correctly. If I understand you correctly, each location in a slice represents a unique (x,y)
coordinate. For each matrix that you have, you want to sample from this exact same location but temporally search through your ~2500 time instances. As such, you need to use all of your loop variables i
, j
and k
to index into your 3D matrix. You also need to access all time slices at position (i,j)
and randomly sample from all of the slices. If I can suggest a small optimization change, we can do this with only two for
loops rather than three, randomly choose 320 points at this position for all of the time slices, and store it into the 3D matrix.
In other words:
clear all;
clc;
% Load datafile
load 1979_1999_tropics_subset_3mmhr.mat
% Create empty maps
rain_fake_timeseries = zeros(1152,241,320);
for i = 1 : size(rain_fake_timeseries,1)
for j = 1 : size(rain_fake_timeseries,2)
rain_fake_timeseries(i,j,:) = datasample(rain_sample_1979_1999(i,j,:), ...
size(rain_fake_timeseries,3), 3);
end
end
save random_clus_fake_timeseries.mat rain_fake_timeseries -v7.3;
Note that I have replaced the dimensions in the for
loop with calls to size
so that you can easily change the size of the matrices and it'll still work without you having to change any constants.
Upvotes: 1