对于循环和Matlab数据从matfile导入

时间:2017-07-21 07:17:48

标签: excel matlab import

从URL下载数据{n}并导出到excel(参见下面的代码):

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')

如果现在想要从保存为URL.m的10个网址列表中下载,那么如何添加上述代码才能实现这一目标?也许在MATLAB R2017a中使用for循环?

1 个答案:

答案 0 :(得分:0)

听起来您可以执行以下操作来加载您的网址

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

根据您将列表保存到.m文件的方式,您可能会有一些细微的变化。如果它是一个名为URLs的1D单元格字符串数组,那么现在它将位于您的工作区中。您可以调整代码以循环遍历URL,如此

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

您会注意到我在xlswrite中使用了循环变量,因此每个网址的数据都存储在工作簿的单独表格中。您可以通过执行诸如跟踪已编写的行数等操作来调整此操作,并相应地将A1更改为目标单元格。