Matlab 2012 Split String Special Character11/18/2021
Let's assume your text file is stored in text.txt: fid = fopen('text.txt') Input text, with each input specified as a character vector, a character array, a cell array of character vectors, or a string array. As such, do something like this. Because you will probably have each line containing a different amount of numbers, let's store each array into a cell array where each element in this cell array will contain the numbers per line.We check to see if the ID returned from fopen is -1 and if that's the case, we couldn't find or open the file so spit out an error. We first use fopen to open up the file for reading. If both s1 and s2 are string arrays or cell arrays of character vectors, then s1 and s2 must be the same size, unless one of them is scalar.Let's go through the above code slowly.Else, we check to see if the first character is. If we read a -1, this means we have reached the end of the file, so get out of the loop. CREATE FUNCTION SPLITSTRING(String NVARCHAR(MAX), Delimiter CHAR(1)) RETURNS Temptable TABLE(ID NVARCHAR(512Now, until we reach the end of the file, get one line of text starting from the top of the file and we proceed to the end.We then place this array into a single cell stored in nums.The end result of this entire code will give you numeric arrays that are based on what you are looking for stored in nums. The resulting output of cellfun will give you a numeric array representation of each value delimited by the character for that line. You can either use a loop to go through each cell, or you can conveniently use ( to allow you to go through each element in this cell and convert the string representation into a numeric value. You need to convert this cell array back into a numeric array, and so what you would need to do is apply str2num to each element in this cell. The result of this will be a cell array of strings where each element is the string representation of your number.
![]() I'm assuming this isn't the case!This could be one approach assuming a uniformly structured data (3 valid numbers per row) - %// Read in entire text data into a cell array%// Find boundaries based on delimiter "%example"Exmp_delim_matches = strcmp(data(1),' '),1:numel(data)))%// Select lines that start with character " " and split lines based on it%// Split selected lines based on the delimiter " "Split_data = regexp(data(matches_idx),' ','split')%// Collect all cells data into a 1D cell array%// Select only non-empty cells and convert them to a numeric array.%// Finally reshape into a format with 3 numbers per row as final outputOut = reshape(str2double(all_data(~cellfun('isempty',all_data))),3,).' %//'%// Separate out lines based on the earlier set boundsOut_sep = out(matches_idx>bound_idx(n) &. If this is not the case, then my code will not work.
0 Comments
Leave a Reply.AuthorSarah ArchivesCategories |