Extra text when using jsondecode - matlab

I am trying to come to the point where I create a graph on a given data that I am supposed to read from a text file.
So I use in my code fopen to open the text file, textscan to scan it, than make a string out of it and by using split I want to cut of the first part of every line and use the second part so that I can decode it into json and then use the information.
So my text file consists of two lines of information:
123456.99 :: working completed: result=0 , data ="{"day":"monday", "breakfast":"sandwich"}"
123456.99 :: working completed: result=0 , data ="{"day":"tuesday", "breakfast":"bread"}"
The first part of my code:
fileID = fopen('test1');
text = textscan(fileID, '%s', 'delimiter','\n','whitespace','');
strLog = string(text{1});
res = split(strLog, "data =");
json_str = res(:, 2)
And as a result I get a 2x1 string array. Output:
json_str =
2×1 string array
""{"day":"monday", "breakfast":"sandwich"}""
""{"day":"tuesday", "breakfast":"bread"}""
This is where I got stuck.
My first idea was to call cellfun and apply jsondecode.
But I got
Error using jsondecode JSON syntax error at line 1, column 4
(character 4): extra text.
But it makes no sence to me, since that should be the " from "day" which for json should be okay!?

In json_str you have quote marks " at the start and end. These need to be removed for jsondecode to work. For example J = jsondecode(json_str{1}(2:end-1)).
You can then use cellfun to process all elements. For example,
S = cellfun(#(x)jsondecode(x(2:end-1)),json_str)

Related

string concatenation from a .txt file matlab

I am trying to concatenate three lines (I want to leave the lines as is; 3 rows) from Shakespeare.txt file that shows:
To be,
or not to be:
that is the question.
My code right now is
fid = fopen('Shakespeare.txt')
while ~feof(fid)
a = fgets(fid);
b = fgets(fid);
c = fgets(fid);
end
fprintf('%s', strcat(a, b, c))
I'm supposed to use strcat and again, I want concatenated and leave them as three rows.
One method of keeping the rows separate is by storing the lines of the text file in a string array. Here a 1 by 3 string array is used. It may also be a good idea to use fgetl() which grabs each line of the text file at a time. Concantenating the outputs of fgetl() as strings may also be another option to ensure the they do not get stored as character (char) arrays. Also using the \n indicates to line break when printing the strings within the array String_Array.
fid = fopen('Shakespeare.txt');
while ~feof(fid)
String_Array(1) = string(fgetl(fid));
String_Array(2) = string(fgetl(fid));
String_Array(3) = string(fgetl(fid));
end
fprintf('%s\n', String_Array);
Ran using MATLAB R2019b

Problems reading a .csv file with ezread

I was trying to read a csv file with ezread https://de.mathworks.com/matlabcentral/fileexchange/11026-ezread and I get the following problem:
Error using textscan
The second input must be a format character vector containing at least one >specifier or a literal field.
Error in ezread (line 66)
data = textscan(fid,format_str,'delimiter',file_delim,'headerlines',1);
I call the function as follows:
tmpName = '/path/file.csv';
structRead = ezread(tmpName, 'r');
I have checked if tmpName is correct with isfile(), so it is a correct path.
First two rows of my file have the following format:
a,b,c,d
1,2,e,f
Do you know where the problem could be ?
Instead ezread, you should use importdata. However it will not recognize separation on comma ,. So you need to add extra line:
tmpName = importdata('/path/file.csv');
structRead = split(a, ',')
The result is:
2×4 cell array
{'a'} {'b'} {'c'} {'d'}
{'1'} {'2'} {'e'} {'f'}

Saving figure without providing filename [duplicate]

this question about matlab:
i'm running a loop and each iteration a new set of data is produced, and I want it to be saved in a new file each time. I also overwrite old files by changing the name. Looks like this:
name_each_iter = strrep(some_source,'.string.mat','string_new.(j).mat')
and what I#m struggling here is the iteration so that I obtain files:
...string_new.1.mat
...string_new.2.mat
etc.
I was trying with various combination of () [] {} as well as 'string_new.'j'.mat' (which gave syntax error)
How can it be done?
Strings are just vectors of characters. So if you want to iteratively create filenames here's an example of how you would do it:
for j = 1:10,
filename = ['string_new.' num2str(j) '.mat'];
disp(filename)
end
The above code will create the following output:
string_new.1.mat
string_new.2.mat
string_new.3.mat
string_new.4.mat
string_new.5.mat
string_new.6.mat
string_new.7.mat
string_new.8.mat
string_new.9.mat
string_new.10.mat
You could also generate all file names in advance using NUM2STR:
>> filenames = cellstr(num2str((1:10)','string_new.%02d.mat'))
filenames =
'string_new.01.mat'
'string_new.02.mat'
'string_new.03.mat'
'string_new.04.mat'
'string_new.05.mat'
'string_new.06.mat'
'string_new.07.mat'
'string_new.08.mat'
'string_new.09.mat'
'string_new.10.mat'
Now access the cell array contents as filenames{i} in each iteration
sprintf is very useful for this:
for ii=5:12
filename = sprintf('data_%02d.mat',ii)
end
this assigns the following strings to filename:
data_05.mat
data_06.mat
data_07.mat
data_08.mat
data_09.mat
data_10.mat
data_11.mat
data_12.mat
notice the zero padding. sprintf in general is useful if you want parameterized formatted strings.
For creating a name based of an already existing file, you can use regexp to detect the '_new.(number).mat' and change the string depending on what regexp finds:
original_filename = 'data.string.mat';
im = regexp(original_filename,'_new.\d+.mat')
if isempty(im) % original file, no _new.(j) detected
newname = [original_filename(1:end-4) '_new.1.mat'];
else
num = str2double(original_filename(im(end)+5:end-4));
newname = sprintf('%s_new.%d.mat',original_filename(1:im(end)-1),num+1);
end
This does exactly that, and produces:
data.string_new.1.mat
data.string_new.2.mat
data.string_new.3.mat
...
data.string_new.9.mat
data.string_new.10.mat
data.string_new.11.mat
when iterating the above function, starting with 'data.string.mat'

Reading and Writing Header to File using MATLAB

I am reading in a .txt-file using importdata:
MC_file = importdata('D:\Simon\Dropbox\SGM\Gigerwald\Results\Multi_SGM_10000.txt');
Data = MC_file.data
Header = MC_file.colheaders
which gives me a struct-variable with the header and the data-body:
data = 10000x52 double
colheaders = 1x52 cell
Now i'd like to change the data, i.e. add some columns to the end of the file and then print the file again with the same header + 5 new columns.
The body can be printed easily using dlmwrite(), e.g. like this:
dlmwrite('SGM.txt',Data,'precision',8,'delimiter','\t','newline','pc','-append')
...but how do I print the header into the file, of which I have a array of cells? I've seen this, but since I end up with 57 columns hard-coding is not an option...
The solution is attainable using repmat. Assuming that your file is tab separated, you can use:
NUM_COLS = 57;
A=cellstr(num2str((1:NUM_COLS)'))';
fid=fopen('newfile.txt','w');
fprintf(fid,repmat('%s\t ',[1,NUM_COLS]),A{:});
fclose(fid);
The result can be previewed with:
sprintf(repmat('%s\t ',[1,NUM_COLS]),A{:})

printing a vector of string in static text box with new lines

I have a bunch of classes that I am iterating through and collecting which classes the student is failing in. If the student fails , I collect the name of the class in a vector called retake.
retake =[Math History Science]
I have line breaks so when the classes print in the command window it shows as:
retake=
Math
History
Science.
However, I am trying display retake in a static text box in Gui Guide so it looks like the above. Instead, the static text box is showing as:
MathHistoryScience
set(handles.text13,'String', retake) % this is what I tried
can you please show me so it prints:
Math
History
Science
It looks to me like you need to add carriage returns.
Assuming you have a cell array with strings (rather than concatenated strings using [], which will give you a single long line), you can do it as follows:
retake = {'Math', 'History', 'Science'};
rString = '';
for ii = 1:numel(retake)-1
rString = [rString sprintf('%s\n', retake{ii}];
end
rString = [rString retake{end}];
Notice the use of '' to denote strings, {} to denote a cell array, '\n' as the end-of-line character, and [a b] to do simple string concatenation.