How to parse an Nx1 string array without looping through N
이전 댓글 표시
I have an Nx1 string array, and I can't figure out how to extract 6 chunks of text out of it and into an Nx6 cell array. The text elements are numbers, but it's simplest to not treat them as numbers at this juncture.
Here is a toy version of the string array, together with code that correctly parses out the necessary elements of CCYYMMDD and hhmm from the first element of the string array:
stringFile = ["nsasondewnpnC1.b1.20020428.184800.cdf"; ...
"nsasondewnpnC1.b1.20020428.220500.cdf"; ...
"nsasondewnpnC1.b1.20020428.235900.cdf"; ...
"nsasondewnpnC1.b1.20020429.013100.cdf"; ...
"nsasondewnpnC1.b1.20020429.182500.cdf"];
charLaunch = textscan(stringFile(1),'%*18c %2c %2c %2c %2c %*c %2c %2c');
charLaunch =
1×6 cell array
{'20'} {'02'} {'04'} {'28'} {'18'} {'48'}
However, both
charLaunchAll = textscan(stringFile,'%*18c %2c %2c %2c %2c %*c %2c %2c');
and
charLaunchAll = cell(5,6);
charLaunchAll = textscan(stringFile(:),'%*18c %2c %2c %2c %2c %*c %2c %2c');
generate the same error message:
Error using textscan
First input must be a valid file-id or non-empty character vector.
Is there a way to extract these pieces of texts out of every array member without building a loop?
채택된 답변
추가 답변 (1개)
Mohammad Sami
2020년 4월 23일
Since the pattern in your string seems to be the same, you can use the format specification to convert the string directly to datetime as follows.
stringFile = ["nsasondewnpnC1.b1.20020428.184800.cdf"; ...
"nsasondewnpnC1.b1.20020428.220500.cdf"; ...
"nsasondewnpnC1.b1.20020428.235900.cdf"; ...
"nsasondewnpnC1.b1.20020429.013100.cdf"; ...
"nsasondewnpnC1.b1.20020429.182500.cdf"];
fmt = "'nsasondewnpnC1.b1.'yyyyMMdd'.'HHmmss'.cdf'";
% the constant portion of your string is enclosed in 'single quotes';
d = datetime(stringFile,'InputFormat',fmt);
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!