Performing formulas on .mat files in MATLAB
2 views (last 30 days)
Show older comments
Dear All,
I have a .mat file in which there are five 2d matrixes (43* 44) where 43 stands for subjects and 44 stands for each frequency step.
I want to average few of the frequencies together ( lets say i want to average 43 data points of 2Hz 3 Hz and 4Hz and place them in a separate mat file under the column of lower delta for all these 43 subjects. Can you guys help me write a code for this?
Regards,
Tanaya
3 Comments
dpb
on 9 Jan 2021
My ANSWER below shows the "how" in generic terms without requiring explictly knowing which column is which frequency. As noted there, if the frequencies are integral steps, then you can compute which column is which or match precisely.
See doc colon for the MATLAB expression to address all rows/columns in subscripting expressions and as the colon operator in expansion of vectors.
Brute force for your case above would be
mnA=mean(A(:,[3:5]),2);
if the array is A. Writing such code with "magic numbers" buried inside it is very inefficient, however, in that you have to rewrite the code to change anything; use general expressions as I show below.
Work through the "Getting Started" sections in the documentation to learn the rudiments of MATLAB syntax and see simple examples of how to use -- it will pay you back in time saved multiples of times over.
Answers (1)
dpb
on 8 Jan 2021
You don't tell us much to go on, but the averaging is simple -- you just have to have a way to find which column(s) are in the frequency range of interest...if the frequency is actually integral steps as your example, it's foolproof to use
f1=2;
f2=4;
ix=iswithin(f,f1,f2);
mnM=mean(M(:,ix),2);
where
f is vector of frequencies matching columns of M
M is one of the matrices/arrays
and iswithin is my utility handy-dandy function
function flg=iswithin(x,lo,hi)
% returns T for values within range of input
% SYNTAX:
% [log] = iswithin(x,lo,hi)
% returns T for x between lo and hi values, inclusive
flg= (x>=lo) & (x<=hi);
>>
to move the compound logical expression to a lower level leaving the toplevel code easier to read/debug.
NB: however, that having five separate arrays of the same structure is an indication of less than optimal data storage in MATLAB -- this way you've got to write the same code five times; if you were to use a 3D array, say, of 43x44x5 you could have one line of code and operate over a loop by plane to accomplish the same thing.
There are other ways to organize the data as well; cell arrays, an array of tables, ...
0 Comments
See Also
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!