简体   繁体   中英

For loop and Matlab data Import from matfile

Data {n} was downloaded from the URL and exported to excel (see the code below):

url='https://data..../..../....json';
data = webread(url);
fnames = fieldnames(data{1});
out = cell(numel(fnames), numel(data));
for n = 1:numel(data)
    for field = 1:numel(fnames)
        temp = data{n};
        try
            out{field, n} = temp.(fnames{field});
        catch
        end
    end
end
out = [fnames, out];
xlswrite('C:\Users\....\.....\test.xlsx', out, 1, 'A1')

If now one wants to download from a list of 10 URLs saved as URL.m , how can the above code be added to achieve that? Perhaps using the for loop in MATLAB R2017a?

It sounds like you could do the following to load your URLs

load('C:\...\URL.m');

Depending how you saved your list to that .m file you then may have some minor variations. If it was a 1D cell array of strings called URLs , then this will now be sat in your workspace. You could adapt your code to loop through the URLs like so

for u = 1:numel(URLs)
    url = URLs{u}; % Assign the url variable to the next value in URLs
    % --- Between the dashes is exactly the same as your previous code ---
    data = webread(url);
    fnames = fieldnames(data{1});
    out = cell(numel(fnames), numel(data));
    for n = 1:numel(data)
        for field = 1:numel(fnames)
            temp = data{n};
            try
                out{field, n} = temp.(fnames{field});
            catch
            end
        end
    end
    out = [fnames, out];
    % --------------------------------------------------------------------
    xlswrite('C:\Users\....\.....\test.xlsx', out, u, 'A1'); % Write
end

You'll notice that I'm using the loop variable within xlswrite so that each URL's data is stored in a separate sheet of the workbook. You may adapt this by doing something like keeping track of the number of rows you have already written, and changing A1 accordingly as the destination cell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM