Change array name inside loop, external data

조회 수: 13 (최근 30일)
juan pimienta
juan pimienta 2020년 4월 29일
댓글: Stephen23 2020년 5월 1일
I'm working with a data set of around 50 Gb so i decided to work by "pieces" calling and eliminating each data set after each calculation has been performed. I have 8 different .mat files, each one containing a cell{1,5} that contains each an array of (1,50) and finally a 2d array of (1024,1024). My question is, can i change somehow the name of the array containing this data inside the calculation loop? Code is below. I have read similar questions, but no similar approach to my problem, the cell arrays i'm trying to read and calculate have already an assigned name.
ld = [5,10,15,20,25,50,75,100];
for i=1:8
load(sprintf('U%i.mat',ld(i)));
for a = 1:1024
for b = 1:1024
for c = 1:50
stad_pmmh(c) = 'U_%i{c}(a,b); %%%%Here is the main issue and where i need a "dynamical naming"
end
STAD_pmmh{a,b} = stad_pmmh;
dev_pmmh(a,b) = std(STAD_pmmh{a,b});
end
end
save(sprintf('dev_%i',ld(i)),'dev_pmmh');
%
clear (sprintf('U_%i',ld(i)));
end

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 4월 29일
Dynamic naming and directly calling load() without any output argument is never a good idea: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval. If the files 'U%i.mat' only contains a single variable, then the following approach will be more suitable.
Change the load() line to
data = load(sprintf('U%i.mat',ld(i))); % data is a struct
f_name = fieldnames(data)
and the load the data like this
stad_pmmh(c) = data.(f_name{:})(a,b);
However, this will fail if the .mat files have multiple variables.
In that case, you will eventually use eval() to create the variable names dynamically, for example using sprintf: https://www.mathworks.com/help/matlab/ref/eval.html
stad_pmmh(c) = eval(sprintf('U_%i{c}(a,b)', i));
  댓글 수: 2
juan pimienta
juan pimienta 2020년 5월 1일
Thanks for your answer, anyway i managed to solve the problem with a couple of conditionals, i'll keep your advice for future works!.
Stephen23
Stephen23 2020년 5월 1일
"...you will eventually use eval() to create the variable names dynamically"
No eval required: either store the output of load in a non-scalar structure (if the fields are the same) or in a cell array (if the fields are different).

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by