Matlab struct with names and sizes of the mat.file

1 回表示 (過去 30 日間)
Robert Bag
Robert Bag 2021 年 5 月 12 日
コメント済み: Walter Roberson 2021 年 5 月 13 日
Hi, I am trying to create a function that asks for mat.file and then I would like t o create a struct which returns the name and size of the variables in the mat.file.
Anyone who knows how to do that?

回答 (1 件)

Walter Roberson
Walter Roberson 2021 年 5 月 12 日
Use whos() with the '-file' option and extract the required data from that.
  11 件のコメント
Robert Bag
Robert Bag 2021 年 5 月 13 日
Walter, is there any way to get whos to obly display specific fields?
Walter Roberson
Walter Roberson 2021 年 5 月 13 日
whos() is built-in, so I cannot look at the source code for it. There is no documented way to get whos() to only display specified fields.
But why are you asking about displaying fields? Your question and comments indicate that you want the information returned as a struct with field 'name' and 'size' . Displaying is a different task.
The below code has been constructed to mimic the output of whos. It might have some fine details wrong about automatic sizing or justification of field widths.
function info = fileinfo(filename)
if ~exist(filename, 'file')
error(message('MATLAB:whos:fileIsNotThere', filename));
end
tinfo = whos('-file', filename);
if nargout > 0
info = struct('name', {tinfo.name}, 'size', {tinfo.size});
else
fields = ["name", "size"; "", ""; string({tinfo.name}.'), cellfun(@(S) strjoin(arrayfun(@string,S),'x'), {tinfo.size}.')];
L = strlength(fields);
widths = max(L,[],1);
fmt = compose(" %%-%ds %%-%ds", max([14, 0], widths));
fprintf('%s\n', compose(fmt, fields(:,1), fields(:,2)))
end
end

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeEnvironment and Settings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by