Mean of several .mat files of a 3-D Matrix - matlab

I have several .mat files, which are all in a 3-D matrix of latitude x longitude x value (70 x 70 x 8760).
It looks like this:
year2000.mat --> (72 x 70 x 8760),
year2001.mat --> (72 x 70 x 8760),until year 2020
I need the long-term mean along the third dimensions-the value. The result should be again a .mat file with 3-Dimension (72 x 70 x 8760). The first and second dimensions don't change.
I am very new to Matlab.

you did well in loading the files but since you know all the files start with year you can do:
fn = dir('year*.mat');
Then, you load the files, but if I understand you correctly you want to mean the years, not each year. so,
data = zeros(72,70,8760);
for n=1:numel(fn)
single_year = load(fn(n).name);
data = data + single_year.variable ;
end
is variable really the name if the variable in each mat file? I just used what you wrote, but you should check what you get if you load a single file.
now the avg is just the sum over the n:
data=data./numel(fn);

Related

How could I add multiple headers to a Matlab txt document

I currently have code that places data collected from a simulation into various txt documents separated by time. However, I would like to add various headers and other information into each document. How would that be possible? Some of the information would be a variable (such as previous ones I put in) and others would be constant for each one.
for nn = 1:TMAX/10
fid = fopen(['word' num2str(nn) '.txt'],'w');
%x and y are defined here for the entire code and for x y and theta to
%have a close access to print
x = x + vel*cos(theta)*dt;
y = y + vel*sin(theta)*dt;
fprintf(fid, '%4.5f\t%4.5f\t%4.5f\n', x,y,theta);
fclose(fid);
ideally the new code would return
ITEM: TIMESTEP (is the header)
1000 (i a variable base off of time (is nn/10))
ITEM: NUMBER OF ATOMS (another header)
32000 (Variable N)
ITEM: BOX BOUNDS pp pp pp (another header)
0 54 (is variable 0-L)
0 54 (is variable 0-L)
0 6.283185307 (is constant 0 to 2 pi)
ITEM: ATOMS id x y Theta (another header)
the last line that isn't written is that I would like to number each particle. Ie Currently the code returns a matrix of the three variables X Y Theta in three columns and I would like the rows to be labeled 1-N.
How could any of this be done? Thank you very much!

Loading multiple .mat files into a matrix and performing operations on it

I have 429 numerical matrices of identical size (107 rows by 36 columns), stored inside sequentially named .mat files (e.g: subj_00000.mat ... subj_00428.mat). Here's what I need to do:
Import into the MATLAB workspace.
After importing, average all of them to generate another matrix, which will also have a dimension of 107x36.
Finally, linearly correlate each column of the average matrix with each column of each of the original 429 matrices, to generate a new matrix of 429 rows and 36 columns.
So far I got to the stage of building a 107 x 36 x 429 array to be filled with my set of matrices.
S = dir(fullfile(D,'subj*.mat')); % D is the path where the .mat files are saved
N = numel(S);
C = cell(1,N); % preallocate cell array
for k = 1:N
S = load(fullfile(D,S(k).name));
C(k) = struct2cell(S);
end
A = cat(3,C{:}); % join all of the original matrices into a 107x36x429 array
M = mean(A,3)
but I get the following error message:
Reference to non-existent field 'name'.
Error in myscript (line 6)
S = load(fullfile(D,S(k).name));
You are looping over S yet overwriting it every time. Rename the S that is inside the loop. While you are at it I would give all your variables meaningful names--there is no need to use a single letter every time. – svdc
Thank you! I renamed
S = load(fullfile(D,S(k).name));
as
T = load(fullfile(D,S(k).name));
and it worked

Modify timeseries data individual values in MATLAB

Going a bit crazy here as I am not managing to use the index referencing for my newly-created timeseries objects.
All I wish to do is query/return/modify the value from a particular date.
i.e. where my timeseries "temp" is daily values for temperature and I want to change the value on January 16th 2008.
My date structure is formatted as such "01-Jan-2008"
I have tried various ways, but not managing! :(
temp('16-Jan-2008')= 25; % Info on this page ref [1]
temp(16) = 25; % 16 referring to the element index
I know that I could go into tstools and modify it manually, but I want to do much further matrix manipulation with the timeseries but am struggling somehow even with the index referencing! Can they not be modified easily in the command window?
Thanks
[1] - http://www.mathworks.co.uk/help/finance/working-with-financial-time-series-objects.html#f13-5213
For 2 vectors
time [size = n by 1] & temp [size = n by 1]
If ur timeseries is a char vector (all rows same length and not cell). U can convert to matlab time nums like
time_tmp = datenum(time,'dd-mmm-yyyy');
Then u can change a temp vector (same length as time)
temp(time_tmp == datenum(2008,1,16)) = 25;
otherwise u can convert ur data to 2 vectors then do above.

extracting data from an existing matrix

I have a matrix containing 4320 entries
for example:
P=[ 26 29 31 33 35 26 29 ..........25]
I want to create 180 matrices and every matrix contains 24 entries,i.e
the 1st matrix contains the 1st 24 entries
the 2nd matrix contains the 2nd 24 entries and so on
I know a simple method but it will take a long time which is:
P1=P(1:24);P2=P(25:48),..........P180=P(4297:4320)
and it is dificult since I have huge number of entries for
the original matrix P
thanks
I'm going to go ahead and assume this is MATLAB-related, in which case you'd use the reshape function:
Px = reshape(P, 24, []);
Px will now be a proper matrix, and you can access each of the 180 "matrices" (actually row vectors, you seem to be confusing the two) by simple MATLAB syntax:
P100 = P(:,100);
You can loop through the items in the index, counting up, creating a new matrix every 24 entries. Modular arithmetic might help:
foreach (var currentIndexInLargerMatrix : int = 0 to 4320)
begin
matrixToPutItIn := currentIndexInLargerMatrix div 24;
indexInNewMatrix := currentIndexInLargerMatrix mod 24;
end
in many languages the modulus (remainder) operator is either "mod" or "%".
"div" here denotes integer division. Most languages just use the virgule (slash) "/".
This obviously isn't complete code, but should get you started.
I think You's answer is the best way to approach your problem, where each submatrix is stored as a row or column in a larger matrix and is retrieved by simply indexing into that larger matrix.
However, if you really want/need to create 180 separate variables labeled P1 through P180, the way to do this has been discussed in other questions, like this one. In your case, you could use the function EVAL like so:
for iMatrix = 1:180 %# Loop 180 times
tempP = P((1:24)+24*(iMatrix-1)); %# Get your submatrix
eval(['P' int2str(iMatrix) ' = tempP;']); %# Create a new variable
end

MATLAB - How to import and plot data from a .mat file to x and y variables?

I have a problem that I thought I knew how I can fix, but apparently I failed ..
I got a .mat file that I created. It has two columns and 25 rows of numbers. I would like to do a loop to get each value in the first column and put it in the X value, and the second column in the Y value. I then need to plot the points on the graph.
I know how to do the loop, and the plotting .. but I failed to extract the data and put them in X and Y values.
This is my trial code:
load figureinfo.mat
for K=1:25
x=X(:,K) ~~ I remember that the code looks something like that to extract ..
y=Y(:,K)
plot(x,y,'o')
hold on
end
How do I get the data and put it in X and Y?
In addition, where is "ROWS" in (:,b)? b=Columns, but where do I put the rows?
Try the following:
load figureinfo.mat; %# assume this contains a matrix called figureinfo
X = figureinfo(:,1); %# numbers from all rows, column 1, into X
Y = figureinfo(:,2); %# numbers from all rows, column 2, into Y
plot(x,y,'o');
Or more simply,
load figureinfo.mat;
plot(figureinfo(:,1), figureinfo(:,2), 'o');
If you don't know the name of the matrix in your .mat file, I recommend:
clear %# clear all variables from workspace
load figureinfo.mat;
whos
which will show the the name, size, and datatype of whatever you just loaded.
If you really want to extract the data in a loop, you have two options:
load figureinfo.mat; %# assume this contains a matrix called figureinfo
X = [];
Y = [];
for ctr = 1:length(figureinfo)
X = [X figureinfo(ctr,1)];
Y = [Y figureinfo(ctr,2)];
end
or (faster because it doesn't keep reallocating X and Y)
load figureinfo.mat; %# assume this contains a matrix called figureinfo
X = zeros(length(figureinfo),1);
Y = zeros(length(figureinfo),1);
for ctr = 1:length(figureinfo)
X(ctr) = figureinfo(ctr,1);
Y(ctr) = figureinfo(ctr,2);
end