How to write values from two different cell arrays to a text file in a specific format?

1 view (last 30 days)
Hi all,
In MatLab, I have two cell arrays with the onset times of two different sets of tones; targets and distractors. Both of these arrays have 12 cells, which contain the onset times for either distractor tones or target tones for a period of 10 seconds (cell 1: 0-10 seconds, cell 2: 10-20 seconds, cell 3 30-40 seconds, etc). Basically, typing in targets{3} would give you an array with all the onset times of target tones in the 30-40 second range. I should be clear that these arrays will not all be the same size because the tone onset times are pseudorandomly generated.
What I would like to do from here is to write the corresponding cells from the target and distractor arrays to a text file. So targets{1} and distractors{1} would be written to the same text file, and same thing for {2},{3}, all the way up to {12}. The important part here is that I need these text files to have a very specific format, shown below w/ some fake data. The curly brackets need to be included and on their own lines, and the data needs to have the square brackets and be separated by commas. targets should be on the line that says "audioData", and distractors go next to distractorData.
{
"audioData":[5972,20250,22901,31500,41650,51342,54028],
"distractorData":[3379,4231,5298,22500,24266,]
}
As a bonus, these text files will also eventually need to be converted into JSON files, which are just like text files but you need to save them with the filename.JSON format. It's not terribly inconvenient for me to go and change this by hand, but if anyone knows how to save the text files as .JSON's, that'd be great! I don't think writecell() will let you use .json...
  1 Comment
Guillaume
Guillaume on 11 Dec 2019
"The curly brackets need to be included and on their own lines"
This requirement is not part of the JSON spec, JSON doesn't care about whitespace.

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 11 Dec 2019
The conversion to JSON is easily done:
cellfun(@(a, d) jsonencode(struct('audioData', a, 'distractorData', d)), youraudiocellarray, yourdistractorcellarray, 'UniformOutput', false)
This can be easily written to individual files, however if the whole lot is intended to be sent to something that parses json, wouldn't you just want one json stream?
  3 Comments
Adam Danz
Adam Danz on 11 Dec 2019
Edited: Adam Danz on 11 Dec 2019
@Matthieu Sherwood, this creates a JSON-formatted text. For examples, see
[update]
I didn't see the last part of your question until now (converting the text file to JSON). Guillaume's answer is more direct that mine.
Guillaume
Guillaume on 11 Dec 2019
JSON is typically used to transmit data between two things (programs/computers/etc.) in a standardised format. If you were to send data from A to B, you'd normally have just one stream with all the data, instead of sending 240 different json strings.
So, if I needed to transmit your 240 levels to another program, I would have just one json string:
%Assuming the cell arrays are row vectors:
jsonencode(cell2struct([youraudiocellarray; yourdistractorcellarray], {'audioData', 'distractorData'}, 1))
%if the cell arrays are column vector change the ; to , in the cell array concatenation and the 1 to 2 for the dim of the cell2struct
which basically wraps the json strings of my original answer into a json array.
json is a very simple format. All you need to know is at https://www.json.org/json-en.html

Sign in to comment.

More Answers (1)

Adam Danz
Adam Danz on 11 Dec 2019
Edited: Adam Danz on 11 Dec 2019
Hi Matthieu,
in your example,
{
"audioData":[5972,20250,22901,31500,41650,51342,54028],
"distractorData":[3379,4231,5298,22500,24266,] % ^ here
} % ^ here
I'm assuming the commas I've pointed to above are not supposed to be there. They would be easy to add in to the solution below. I also assume the double quotes surrounding the variable names are intentional but they would be very easy to removed if they aren't desired.
See the inline comments for details and if you have any questions please leave a comment.
% Create demo data: 12 row vectors of random ascending integers
target = arrayfun(@(x) {sort(randi(99999,1,x))}, randi(10,1,12)+5);
nVals = cellfun(@numel,target); %number of target times per element
distractors = arrayfun(@(x) {sort(randi(99999,1,x))}, nVals);
% Identify where the files should be saved
textfilePath = 'C:\Users\skippy\Documents\MATLAB'; % full path to directory
% Write target and distractor times to individual text file
nVecs = numel(target); %number of target times
for i = 1:nVecs
% Create text file
fname = sprintf('file_%d.txt',i); % name the current text file
fid = fopen(fullfile(textfilePath, fname),'w+'); % open & clear / create text file
if fid < 0
error('The text file could not be created.')
end
% write the data for iteration i
str = sprintf('{\n "audioData":[%s]\n "distractorData":[%s]\n}',...
strtrim(regexprep(num2str(target{1}),' +',' ')), ...
strtrim(regexprep(num2str(distractors{1}),' +',' ')));
fprintf(fid,str,'s');
% Close text file
fclose(fid);
end
Result : (copied from text file; using random input variables)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!