필터 지우기
필터 지우기

Assign a cell data that starts with a regular expression

조회 수: 1 (최근 30일)
yp78
yp78 2021년 12월 7일
편집: yp78 2021년 12월 7일
An m-file contains a (1 by 4) cell data that may have different name, for example Fsim, FsimData, FsimName etc.
What I want to do is after loading the m-file, assign the cell data to a new variable called 'myData' as long as their name start with 'Fsim'.
How can I achieve this?
% Loading the file
load(fileName,'.mat')
% The file contains only one cell data (1 by 4), which may be named
% differently: Fsim, FsimData, FsimName etc.
% I want to assign the cell data to 'myData' as long as the cell name start with 'Fsim'.
myData=Fsim(followed by regular expression);

채택된 답변

Stephen23
Stephen23 2021년 12월 7일
편집: Stephen23 2021년 12월 7일
Always LOAD into an output variable! That will make your code much more reliable, and makes this task easier.
Method 1: the simplest approach is to use LOAD's syntax which already supports regular expressions:
fnm = sprintf('%s.mat',fileName);
raw = load(fnm,'-regexp','^Fsim');
myData = struct2cell(raw)
Method 2: check the output variable's fieldname:
raw = load(fnm);
fld = fieldnames(raw);
assert(numel(fld)==1,'You said only one variable!')
idx = startsWith(fld,'Fsim'); % or STRNCMP
if idx
myData = raw.(fld{1}); % dynamic fieldname
end
Method 3: use STRUCT2CELL and some indexing, e.g.:
obj = struct2cell(raw);
myData = obj(idx);
  댓글 수: 1
yp78
yp78 2021년 12월 7일
편집: yp78 2021년 12월 7일
Thanks so much for the tips. I was doing something similar to method 2, but the use of 'fieldnames' was something that I was missing through out.

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

추가 답변 (0개)

카테고리

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

태그

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by