【问题标题】:How can I implement for-loop to calcuate partial area of the curve in MATLAB?如何实现for循环来计算MATLAB中曲线的部分面积?
【发布时间】:2015-09-05 19:14:46
【问题描述】:

我在具有 100 行和 300 列的 excel 文件中有大型数据集。第一行是来自 (y1:y300) 的变量的名称,其余数据是数字。我有兴趣计算 x 轴的 2 个固定点之间存在的部分 AUC。 我可以使用@ShellFish 解决方案How do I calculate the partial area under a curve with MATLAB? 来做到这一点。现在我想实现一个循环,它可以计算从 y1 到 y300 的每个 y 值的部分面积。我怎样才能使用for循环来实现这一点?我使用了这段代码。我使用 MATLAB 导入函数导入了 .xls 文件。

    data = importfile('test.xls','Sheet1','A2:AZ100');
    y1 = data(:,1);
    y2 = data(:,2);
    y3 = data(:,3);
    y4 = data(:,4);
    y5 = data(:,5);
...
x = [-1000:10:1000];

startingIndex = find(x==-350);
endingIndex = find(x==-100);

desiredX = x(startingIndex:endingIndex);
desiredY = y1(startingIndex:endingIndex);
area = trapz(desiredX,desiredY);
area

我每次尝试for循环计算desiredY是

for i=y1:y100
    desiredY = i(startingIndex:endingIndex);
    area = trapz(desiredX,desiredY);
    area
end

但是我的代码有些地方非常错误..无法正常工作。

如果有人可以帮助我更正此代码,那就太好了。

【问题讨论】:

    标签: excel matlab


    【解决方案1】:

    这里有几个问题。首先,您不能像这样为for 循环定义迭代器。其次,没有理由显式定义y1, y2, ..., yn,您可以直接寻址data 数组。一想到把这些都写出来,我的手指就疼了:(

    对一些示例数据和代码使用链接问题:

    % Set up sample data
    data = rand(100,3);
    x = 0:100;
    
    startingIndex = find(x == 20);
    endingIndex = find(x == 80);
    desiredX = x(startingIndex:endingIndex);
    
    % Preallocate
    [nrows, ncolumns] = size(data);
    desiredY = zeros(ncolumns, 1);
    area = zeros(ncolumns, 1);
    
    for ii = 1:ncolumns
        desiredY = data(startingIndex:endingIndex, ii);
        area(ii) = trapz(desiredX, desiredY);
    end
    

    这会遍历data 的每一列并执行链接集成,将结果存储在area 中。 area的每个索引对应y中的列。

    【讨论】:

      猜你喜欢
      • 2015-08-10
      • 2012-01-29
      • 2017-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-24
      • 2021-04-18
      相关资源
      最近更新 更多