在MATLAB中存储for循环向量的更有效方法?
我试图存储for循环中的列向量 请参阅以下代码:在MATLAB中存储for循环向量的更有效方法?,matlab,Matlab,我试图存储for循环中的列向量 请参阅以下代码: for i = 1:10 a=rand(10,1) astore = [a a a a a a a a a a a] end 我知道必须有一个更有效的方法来做到这一点。特别是如果我在哪里,比如说I=1:5000?如注释中所述,您希望附加到astore,而不是覆盖每个循环 为了提高内存效率,您应该预先分配输出 k = 10; % number of iterations aHeight = 10; % Height of each a matri
for i = 1:10
a=rand(10,1)
astore = [a a a a a a a a a a a]
end
我知道必须有一个更有效的方法来做到这一点。特别是如果我在哪里,比如说I=1:5000?如注释中所述,您希望附加到astore,而不是覆盖每个循环 为了提高内存效率,您应该预先分配输出
k = 10; % number of iterations
aHeight = 10; % Height of each a matrix in the loop.
astore = NaN( aHeight, k );
for ii = 1:k
a = rand( aHeight, 1 );
astore( :, ii ) = a;
end
我假设aHeight与您的示例一致,但如果不一致,则可以使用单元格数组
k = 10;
astore = cell( 1, k );
for ii = 1:k
a = rand( 10, 1 ); % could be anything
astore{ ii } = a;
end
预分配比使用astreend+1=a或astore=[astore,a]等方法在循环中追加要好。尽管这两个选项都是有效的。阅读关于repmat的内容。for循环是无用的,每次迭代后都会覆盖astore。在for循环创建一个空的astore矩阵之前,astore=[],然后在for循环中:astore=[astore a]@HansHirse谢谢,但上面是我的一个完整的最小示例,我实际上正在运行一个回归,每次@obchardon的方法都能完美地工作时,我都会得到参数值,你能回答这个问题吗!