Add large amount of variables
2 views (last 30 days)
Show older comments
Hello, I have a set of variables which are all Matrixes and their name is usually "Hsig_day_time". I would like to add them all but it there are about 120 and possibly there will be more than 1000.
Is there a way to add them all without writting each variable name in a line?
7 Comments
Stephen23
on 9 May 2022
"I am not sure if it is possible to load them as a struct. At least I can't do it."
Accepted Answer
dpb
on 9 May 2022
OK, I'll just make another Answer so previous conversation doesn't distract
Brute force; may be something a little more clever possible, but...
S=load('IBERIA.mat','-regexp', '^Hsig'); % load the variables beginning with Hsig only
C=struct2cell(S); % turn the fields into cells in cell array
A=C{1}; % begin accumulator for sum
for i=2:numel(C) % and iterate over the size of C
A=A+C{i}; % sum each array
end
mnA=A/numel(C); % compute mean
Above doesn't deal with NaN -- I noticed there are at least some matrices with NaN in them; I didn't search for which or where. I did note that the first 10 locations in both directions are finite.
You'll know better what to do with those locations...
3 Comments
Image Analyst
on 9 May 2022
@Magnus Schneider can you please click the "Accept this answer" link to award @dpb "Reputation Points" and to let others know it's been solved. Thanks in advance. 🙂
More Answers (1)
dpb
on 9 May 2022
Edited: dpb
on 9 May 2022
Don't try to explain in words; show us precisely what the external software generates.
" They are all inside a .mat file..."
Then at a minimum show us what
whos -file TheFileName.mat
returns for one of these files.
Even better would be to attach one here..."help us help you"
The initial (following) was written before I saw the above comment so presumed each was a separate file.
If they are 2D arrays and the dimensions are not humongous for each, then you can simply read each into a 3D array where each file is a plane and use mean(A,3)
If the total won't fit in memory, then a mean is simply a sum which can be computed as a running summation with only one file at a time, then divide the sum by the total number of files.
Either is a basically trivial task to iterate over all files in a particular location.
See Also
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!