Is it possible to use vertcat with dot notation?
조회 수: 1 (최근 30일)
이전 댓글 표시
EDITED Is it possible to use vertcat with dot notation?
This is an example once I extract names from Excel files contained in a folder:
%input
filename = dir(fullfile(directory,'*file*'));
% output
>> filename
filename =
3×1 struct array with fields:
name
folder
date
bytes
isdir
datenum
>> filename.name
ans =
'file_1.xlsx'
ans =
'file_2.xlsx'
ans =
'file_3.xlsx'
% try to concatenate vertically the three files' names
>> vertcat(filename{:}.name)
Brace indexing is not supported for variables of this type.
댓글 수: 7
Jiri Hajek
2022년 12월 13일
Ok, you can put the names into a single variable, but considering the number of characters in each may be different, the most natural choice is cell array (column):
fileNameColumn = {filename.name}';
채택된 답변
Stephen23
2022년 12월 13일
이동: Stephen23
2022년 12월 13일
"The error is being caused by the fact that filename is not a struct."
FILENAME is a struct (as returned by DIR). Curly brace indexing is not defined for structures (see the error message).
"Is it possible to use vertcat with dot notation?"
Of course, you can use any comma-separated list as the inputs to VERTCAT:
S = struct('X',{'hello','world'}) % content have same number of columns...
vertcat(S.X) % so VERTCAT is possible but fragile. Creates a character matrix.
But I would not recommend it because it is very fragile code: using VERTCAT on the structure from DIR() assumes that all of the filenames have exactly the same length, otherwise your code will throw an error:
S = struct('X',{'a','bcd'}) % content have different number of columns...
vertcat(S.X) % which is why VERTCAT is a bad approach.
As Jonas correctly wrote, you should probably use a cell array: {filename.name}
Or, simply refer directly to the content of the structure array.
추가 답변 (2개)
Peter Perkins
2022년 12월 13일
Depending on what you are doing, you may find it convenient to turn that struct into a table (which wil automatically vertcat the file names for you):
s = dir
t = struct2table(s)
댓글 수: 2
Stephen23
2022년 12월 13일
편집: Stephen23
2022년 12월 13일
"which wil automatically vertcat the file names for you"
Strictly speaking it creates a cell array of character arrays, rather than vertical concatenation of the field content:
S = dir();
T = struct2table(S)
T.name % cell array, not vertical concatenation of char vectors.
Jonas
2022년 12월 14일
if you just want to have all file names available, you could use { }
e.g. in a cell array
{filename.name}
if you do not need further information from the dir out beside the name, you could also abbreviate it to one line
{dir(fullfile(directory,'*file*')).name}
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!