How to convert 'inputdlg' output into text file? - arrays

I am writing a script that displays a character array (I would use a string array but inputdlg requires char), allows the user to edit the array, and outputs the new array into a text file.
However, I am running into the issue of not being able to format the output (vals1) into a text file. I think part of the problem is that the inputdlg command outputs a 1x1 array, which is difficult to convert back into the line-by-line format that I started with (in this case arr).
The code below outputs a single line read by column rather than row: "A1ReB2otC3bcD4e E5re 6tt 7 c 8S 9m i t h ". I'm not sure how I would convert this since the charvals1 (the inputdlg output) returns the same string of characters.
Is there a way to either return a row-by-row output (rather than the 1x1 array string) after the user inputs a new array, or print a reformatted version of the inputdlg output (including line breaks)?
arr = char(["ABCDE";
"123456789";
"Robert Smith";
"etc etc"])
% User updates the array
prompt = {'Update content below if necessary'};
dlgtitle = "Section 2";
dims = [30 50];
definput = {arr};
charvals1 = inputdlg(prompt,dlgtitle,dims,definput);
vals1 = convertCharsToStrings(charvals1);
% Outputting the updated array to text file
prompt = {'Enter desired input file name'};
dlgtitle = "Input Name";
dims = [1 35];
definput = {'Input Name'};
fileName = inputdlg(prompt,dlgtitle,dims,definput);
selected_dir = uigetdir();
fileLocation = char(strcat(selected_dir, '\', string(fileName(1)),'.txt'));
txtfile = fopen(fileLocation,'wt');
fprintf(txtfile, '%s\n', vals1) ;

Don't use convertCharsToStrings, since it will operate along the first dimension of the character array (you could transpose the character array first, but then the 'linebreaks' are lost).
You can convert the character array that you obtain to a string and then trim the whitespace. This can be written to a textfile without any problem with the code that you have already.
charvals1 = inputdlg(prompt,dlgtitle,dims,definput);
vals1 = string(charvals1{1}); % note the {1} to access the contents of the cell array.
vals1 = strtrim(vals1);
And don't forget to close the txtfile:
txtfile = fopen(fileLocation,'wt');
fprintf(txtfile, '%s\n', vals1);
fclose(txtfile);

Related

Add string to 1-D cell array without determing its length in MATLAB

I have some strings in file.txt and I want to add all of it to a cell array.
But the problem is a number of strings in file are unknown and I don't want to count. I want each time I read 1 string in file (from top to bottom), I'll add it to cell array.
Example:
**file.txt**
ABC
DEFG
HI
JKLMNO
--> cellarray(1) = 'ABC', cellarray(2) = 'DEFG', cellarray(3) = 'HI', cellarray(4) = 'JKLMNO'
I'm using MATLAB R2014b. How can I do this?
You can use textscan to load your entire file into a cell array of strings. The result is going to be a 1 x 1 cell array because you only have one format specifier (%s) but that cell array will contain another cell array of all of the lines in the file.
fid = fopen('file.txt', 'rt');
data = textscan(fid, '%s', 'delimiter', '\r\n');
C = data{1};
%// 'ABC'
%// 'DEFG'
%// 'HI'
%// 'JKLMNO'
You can get a line from text file using the fgets function in MATLAB (Documentation)

Matlab join array of strings

In ruby and other languages, I can create an array, push an arbitrary number of strings and then join the array:
ary=[]
...
ary.push some_str
ary.push some_other_str
...
result = ary.join ""
How do I accomplish this in matlab?
User story: my plot legend is composed of a variable number of strings. The number of strings is determined runtime, so I want to declare the array, add strings dynamically and then join the array to the legend string in the end of the script.
In MATLAB, String joining happens like the following
a = 'ding';
b = 'dong';
c = [a ' ' b]; % Produces 'ding dong'
P.S. a typeof(c,'char') shows TRUE in MATLAB because it "joins" all characters into C.
Suppose you want to start with an empty char placeholder. You can do this.
a = ``; % Produces an empty character with 0x0 size.
Then you can keep adding to the end of it; like this:
a = [a 'newly added'] % produces a = "newly added"
To prove that it works, do this again:
a = [a ' appended more to the end.'] % produces a = "newly added appended more to the end."
You can always use the end keyword that points to the last index of an array, but in this case you need to append to end+X where X is the extra number of characters you are appending (annoyingly). I suggest you just use the [] operator to join/append.
There is also this strjoin(C, delim) function which joins a cell C of strings using a delim delimiter (could be whitespace or whatever). But cheap and dirty one is the one I showed above.

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

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');
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.
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,' ')

Best way to compare data from file to data in array in Matlab

I am having a bit of trouble with a specific file i/o in matlab, I am fairly new to it still so some things are still a bit of a mystery to me. The input file is structured as so:
File Name: Processed_kplr003942670-2010174085026_llc.fits.txt
File contents- 6 Header Lines then:
1, 2, 3
1, 2, 3
basically a matrix of about [1443,3] with varying values
now here is the matrix that I'm comparing it to:
[(0123456, 1, 2, 3), (0123456, 2, 3, 4), (etc..)]
Now here is my problem, first I need to know how to properly do the file input in a way which can let me compare the ID number (0123456) that is in the filename with the ID value that is in the matrix, so that I can compare the other columns of both. I do not know how to achieve this in matlab. Furthermore, I need to be able to loop over every point in the the matrix that matches up to the specific file, for example:
If I have 15 files ranging from 'Processed_0123456_1' to 'Processed_0123456_15' then I want to be able to read in the values contained in 'Processed_0123456_1'and compare them to ANY row in the matrix that corresponds to that ID (0123456). I don't know if maybe accumaray can be used for this, but as I said I'm not sure.
So the code must:
-Read in file
-Compare file to any point in the matrix with corresponding ID
-Do operations
-Loop over until full list of files in the directory are read in and processed, and output a matrix with the results.
Thanks for any help.
EDIT: Exact File Sample--
Kepler I.D.-----Channel
[1161345]--------[84]
-TTYPE1--------TTYPE8------------TTYPE4
['TIME']---['PDCSAP_FLUX']---['SAP_FLUX']
['BJD - 2454833']--['e-/s']--------['e-/s']
CROWDSAP --- 0.9791
630.195880143,277165.0,268233.0
630.216312946,277214.0,268270.0
630.23674585,277239.0,268293.0
630.257178554,277296.0,268355.0
630.277611357,277294.0,268364.0
630.29804426,277365.0,268441.0
630.318476962,277337.0,268419.0
630.338909764,277403.0,268481.0
630.359342667,277389.0,268463.0
630.379775369,277441.0,268508.0
630.40020817,277545.0,268604.0
There are more entries than what was just posted but they go for about 1000 lines so it is impractical to post that all here.
To get the file ID, use regular expressions, e.g.:
filename = 'Processed_0123456_1';
file_id_str = regexprep(filename, 'Processed_(\d+)_\d+', '$1');
file_num_str = regexprep(filename, 'Processed_\d+_(\d+)', '$1')
To read in the file contents, assuming that it's all comma-separated values without a header, use textscan, e.g.,
fid = fopen(filename)
C = textscan(fid, '%f,%f,%f') % Use as many %f specifiers as you have entries per line in the file
textscan also works on strings. So, for example, if your file contents was:
filestr = sprintf('1, 2, 3\n1, 3, 3')
Then running textscan on filestr works like this:
C = textscan(filestr, '%f,%f,%f')
C =
[2x1 int32] [2x1 int32] [2x1 int32]
You can convert that to a matrix using cell2mat:
cell2mat(C)
ans =
1 2 3
1 3 3
You could then repeat this procedure for all files with the same ID and concatenate them into a single matrix, e.g.,
C_full = [];
for (all files with the same ID)
C = do_all_the_above_stuff;
C_full = [C_full; C];
end
Then you can look for what you want in C_full.
Update based on updated OP Dec 12, 2013
Here's code to read the values from a single file. Wrap this all in the the loop that I mentioned above to loop over all your files and read them all into a single matrix.
fid = fopen('/path/to/file');
% Skip over 12 header lines
for kk = 1:12
fgetl(fid);
end
% Read in values to a matrix
C = textscan(fid, '%f,%f,%f');
C = cell2mat(C);
I think your requirements are too complicated to write the whole script here. Nonetheless, I will try to give some pointers to help. Disclaimer: None of this is tested, just my best guess. Please expect syntax errors, etc. I hope you can figure them out :-)
1) You can use the textscan function with the delimiter option to get data from the lines of your file. Since your format varies as it does, we will probably want to use...
2) ... fgetl to read the first two lines into strings and process them separately using texstscan. Such an operation might look like:
fid = fopen('file.txt','w');
tline1 = fgetl(fid);
tline2 = fgetl(fid);
fclose(fid);
C1 = textscan(tline1,'%s %d %s','delimiter','_'); %C1{2} will be the integer we want
C2 = textscan(tline2,'%s %s'),'delimiter,':'); %C2{2} will be the values we want, but they're still a string so...
mat = str2num(C2{2});
3) Then, for the rest of the lines, we can use something like dlmread:
mat2 = dlmread('file.txt',',',2,0);
The 2,0 specifies the offset in 0-based rows,columns from the start of the file. You may need to look at something like vertcat to stitch mat and mat2 together.
4) The list of files in the directory can be found with the dir command. The filename is an attribute of the structure that's returned:
dirlist = dir;
for i = 1:length(dirlist)
filename = dirlist(i).name
%process your files
end
You can also pass matching strings to dir, like so:
dirlist = dir('*.txt');
which will find all of the files with extension .txt.
5) You can very easily loop through the comparison matrix:
sze = size(comparisonmatrix);
for i = 1:sze(1)
%compare comparisonmatrix(i,1) to C1{2}
%Perform whatever operations you need
end
Hope that helps!

Displaying more than one String Array in Android

I am currently building an Book-App (sort of). So there are a lot of Strings, and the User can choose from which line he wants to start reading. So e.g there are 200 Strings in a String Array for Chapter one. And the User wants to start reading at Line 20(because he read the Lines before already). How can I display all the Strings from 20-200?
I have got:
Resources res = getResources();
String[] Book= res.getStringArray(R.array.ChapterOne);
TextView ChapterOne= (TextView) findViewById(R.id.Text);
SuraAlFateha.setText(Book[20]);
But This just diplays the Line 20. But I want it to Display All the Lines following from 20 (20-200).
How can I do this?
Thank you.
When you set the text you need to set all the text at once, like:
String resultString = '';
for ( int i = 20; i < Book.length; i++ )
resultString = resultString + "\n" + Book[i];
SuraAlFateha.setText( resultString.substring( 1 ) );
or something similar.
You should however calculate how much space you need and reserve it before starting the string appending or else your runtime and memory usage might get sky high.
Book[20] will simply give you the 20th element of the array, if you wish to get text for 20 through the end, you'll need to join the range of elements into a string.
You can use text and array utils to make this easy.
String joinedLines = TextUtils.join("\n", java.utils.Arrays.copyOfRange(Book, 20, Book.length));
SuraAlFateha.setText(joinedLines);

Resources