MATLAB Answers

a sum of the many 3d arrays (just third dimension, and first and second stay steady)

2 views (last 30 days)
Hey all
I have a 408 3d single arrays. Each one is (720*360*12).
I want to write a code to sum the third dimension of all, without any change in the first and second ones.
So, in the end, I would like to have: 720*360*408 3d array.
As I am new to this topic, I would be appreciated if you could help me.

  2 Comments

Daniel M
Daniel M on 27 Oct 2019
First you need to concatenate all your matrices into a big 4D one, and sum them over the third dimension. If you are reading them in from files, this should be very simple to do with a loop and there are many tutorials on this. If you have created 408 individual matrices, well... this is precisely why it is not recommended to name your variables dynamically. And you should continue to read this page more closely.
Behzad Navidi
Behzad Navidi on 27 Oct 2019
Like this example:
A=(720*360*12)
B=(720*360*12)
C=(720*360*12)
So:
SUM=(720*360*(12+12+12))
here is for 3 years, and I want it for 34 years.
Sitll I need to produce 4D matrix?
Thank You

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 27 Oct 2019
No, you do not need to build a 4D array.
projectdir = 'NameOfDirectory';
dinfo = dir(fullfile(projectdir, '*.mat'));
filenames = fullfile(projectdir, {dinfo.name});
numfiles = length(filenames);
total_values = [];
for K = 1 : numfiles
thisfile = filenames{K};
filedata_struct = load(thisfile);
fn = fieldnames(filedata_struct);
first_field = fn{1};
this_data = filedata_struct.(first_field);
if K == 1
total_values = this_data;
else
total_values = total_values + this_data;
end
end
The above code would have to be altered to suit the way that data is stored in your files.

  0 Comments

Sign in to comment.

More Answers (0)

Sign in to answer this question.