read each line of a text up to the first space into a cell array in MATLAB

北慕城南 提交于 2020-01-03 03:19:06

问题


I have a multi line text file that in each line has 3 words separated by some spaces. I want to write the first word of each line into a nX1 cell array, so that:

cell{1}{1}=line1_1stword

cell{1}{2}=line2_1stword
.
.
.

How can I do that? I know that the following command reads each line into a line of the cell, but I want just the first word.

fid = fopen(`myFile.ext`)
allData = textscan(fid,'%s','Delimiter','\n');

回答1:


Try this -

fid = fopen('myFile.ext')
allData = textscan(fid,'%s','Delimiter','\n')

%%// Read in the first word from each row of data
outcellarray = regexp(allData{:},'^([\w\-]+)','match')

%%// Store all the first words into a single cell array of strings
outcellarray = vertcat(outcellarray{:})

Inspired by this code.




回答2:


You can use [strsplit](http://www.mathworks.in/matlabcentral/fileexchange/21710-string-toolkits/content/strings/strsplit.m"Download the file from MatlabCentral here") function.

cell=strsplit(text,' ')


来源:https://stackoverflow.com/questions/23357320/read-each-line-of-a-text-up-to-the-first-space-into-a-cell-array-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!