Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/google-app-engine/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Matlab 如何循环通过与另一个向量对应的向量_Matlab - Fatal编程技术网

Matlab 如何循环通过与另一个向量对应的向量

Matlab 如何循环通过与另一个向量对应的向量,matlab,Matlab,我有一列从1981年到2000年的年份,对应于商品的另一列价格。我试着做一个循环,只遍历1990年到2000年的年份,并按照与年份相关的顺序打印价格。到目前为止,我已经有了这段代码,但我不知道为什么它不会运行,任何帮助都会很棒 for x=1:year == 1990:2000 v = find(isfinite(price)); v end 如果您的输入数据是这样的,第一列是年份,第二列是价格 data = [1990, 2.50; 1991, 3.00;

我有一列从1981年到2000年的年份,对应于商品的另一列价格。我试着做一个循环,只遍历1990年到2000年的年份,并按照与年份相关的顺序打印价格。到目前为止,我已经有了这段代码,但我不知道为什么它不会运行,任何帮助都会很棒

for x=1:year == 1990:2000
v = find(isfinite(price));
v
end 

如果您的输入数据是这样的,第一列是年份,第二列是价格

data = [1990, 2.50;
        1991, 3.00;
        ...
        2000, 4.00];
您可以循环使用for循环中的年份(注意语法以及它与您的帖子中的年份的比较),然后找到第二列,其中价格对应于使用for循环的年份

即使您的数据位于两个不同的数据结构中,您也可以执行类似的操作(只要它们大小相同)

编辑

如果你是for循环厌恶者,你可以在没有for循环的情况下做同样的事情。最可靠的解决方案是使用

这将返回一个单元格数组,其中每个元素都是给定年份的所有价格

但是,如果您保证每年只有一个价格,您可以省略
统一输入,您将得到一个价格数组

annualPrices = arrayfun(@(x)prices(years == x), years);

好处之一是,这两种方法都不需要对数据进行额外的操作(如排序)

示例1:

让我们制作一个矩阵来保存您的数据:

M = ones(100,2);  % 1st column for the year and the second column for the prices
M(:,1) = (1951:2050).';
M(:,2) = rand(100,1);
您的问题的一行可以如下所示:

M((M(:,1)<= 2000 & M(:,1) >= 1990),2)
现在使用以下一个衬里:

sortedPrices((sortedYears<= 2000 & sortedYears >= 1990));
sortedPrices((sortedyars=1990));

它不会运行,因为您似乎刚刚发明了一些语法!你在哪里读到x=1:year==1990:2000的
是有效的?谢谢大家,这是一个大问题help@Suever,无需使用for循环。@NKN我完全同意。我试图让它尽可能简单明了地为用户(类似于他们的初始代码),而不会混淆太多。我将添加非for循环版本。@NKN话虽如此,我认为一个无关的
排序
操作并不比for循环好,特别是考虑到MATLAB的JIT编译。@Suever很好的更新!我认为排序> <代码>是在Matlab中用C++实现的,与 > ARRAYFUNION/COD>一样,但是对于纯循环,循环可以慢一些。
M = ones(100,2);  % 1st column for the year and the second column for the prices
M(:,1) = (1951:2050).';
M(:,2) = rand(100,1);
M((M(:,1)<= 2000 & M(:,1) >= 1990),2)
[sortedYears,Idx] = sort(years);    % sort the years vector
sortedPrices = prices(Idx);         % use the index to sort the prices in the same order
sortedPrices((sortedYears<= 2000 & sortedYears >= 1990));