How may I dynamically refer to a loaded mat array to modify or save it

조회 수: 1 (최근 30일)
Will Kinsman
Will Kinsman 2015년 12월 11일
편집: Stephen23 2019년 6월 19일
I am trying to write a simple piece of code where I provide a function with a list name (as a string) and a new string to add to the list (also a string). It will then load that library, add it to the list, sort it, and re-save it. I seem to be getting stuck how to dynamically reference the list name. I desire to do this so that I may add new entries to many other lists I have on my computer quickly with the console.
function addtolist(list,string)
load([list '.mat']); %%%this line works fine
list = vertcat([list '.mat'],string); %%%this line is incorrect
list = sort(list);
save([list '.mat']); %%%this line also incorrectly references the cultures list
end
INPUT: addtolist('Cultures','Armenian') OUTPUT: Nothing (old file is overwritten with line of data)
Thanks in advance for any help here,
William

답변 (3개)

Walter Roberson
Walter Roberson 2015년 12월 11일
편집: Walter Roberson 2015년 12월 11일
In particular use
filename = [list '.mat']
data = load(filename);
data.(list) = sort([data.(list); {string}]);
save(filename, 'data', '-struct');
I explicitly used cell array form as vertcat() of a char array does not work if the new item is not the same width but there is no problem with cell arrays.

Stephen23
Stephen23 2015년 12월 11일
편집: Stephen23 2019년 6월 19일

Will Kinsman
Will Kinsman 2015년 12월 11일
편집: Will Kinsman 2015년 12월 11일
The code ended up looking like this and used the eval() function
function addtolist(list,string)
filename = [list '.mat'];
data = load(filename);
data = sort([data.(list); {string}]);
eval([list '= data']);
save(list,list);
I do understand the danger of using dynamically referenced variables, however this is only 5 lines of code and is meant to be used as quick tool entirely independent of all other code. Thank you for the help!
  댓글 수: 1
Stephen23
Stephen23 2015년 12월 11일
편집: Stephen23 2015년 12월 12일
Hopefully no one will believe that it is a good solution. Please read the better answers below.

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by