Info

This question is closed. Reopen it to edit or answer.

How do I read this file and extract the data to plot and average it

1 view (last 30 days)
I am relatively new to matlab and my professor has given me a programming assignment ( I have recieved permission to recieve outside help and this is not the full extent of the assignment) . TLDR, my professor wants me to take a series of json data files and read them, do some basic integer operations on them and average them by week. My issue is how to extract the data properly. My attempts at this, are written below, but it seems that my current methods leave the data as a struct of strings, where as i need to read the columns at integers. Any ideas or help in the proper direction will be much apprieciated, but I would prefer code snippets or examples rather than the code being written for me because I want to understand the methods. Attached is the dataset my professor gave me, and I am only focusing on the first dataset for the time being.
text = fileread('steps-2018-01-02.json');
jan = jsondecode(text)
%B = arrayfun(func,A)
test = jan.value
%X = str2num(chr)
%value = getfield(S,field)
  1 Comment
Rik
Rik on 6 Oct 2020
This time I edited your question for you. Next time, please use the tools explained on this page to make your question more readable.

Answers (2)

Rik
Rik on 6 Oct 2020
Good call on not using str2num, you should consider using str2double (or textscan or datetime) instead:
[date,value]=read_json_file('steps-2018-01-02.json');
function [date,value]=read_json_file(fn)
text = fileread(fn);
data = jsondecode(text);
value=str2double({data.value});
date=datetime({data.dateTime},'InputFormat',____);
end
  2 Comments
Major Grant
Major Grant on 6 Oct 2020
Thank you for reformatting my question, I tried executing your code, however I was left with an error on compliation on the date line.
Rik
Rik on 6 Oct 2020
Did you fill in the date format? And what release are you using? And what is the full error message?

Ameer Hamza
Ameer Hamza on 6 Oct 2020
Here is an alternate method if you want to keep the struct format
str = fileread('steps-2018-01-02.json');
s = jsondecode(str);
x = cellfun(@str2double, {s.value}, 'uni', 0);
[s.value] = x{:};
dt = cellfun(@(x) datetime(x, 'InputFormat', 'MM/dd/yy HH:mm:ss'), {s.dateTime}, 'uni', 0);
[s.dateTime] = dt{:};
  2 Comments
Major Grant
Major Grant on 6 Oct 2020
Thank you for this, I am now trying to plot this struct, but it is throwing me a slew of errors, would you know the reason why?
Ameer Hamza
Ameer Hamza on 6 Oct 2020
Edited: Ameer Hamza on 6 Oct 2020
Try this
plot([s.dateTime], [s.value])
After running the code in my answer.
If execution speed is important, then it will be helpful if you first convert the struct array to a table before doing the conversion and plotting.

Tags

Community Treasure Hunt

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

Start Hunting!