MATLAB:添加向量元素,直到达到一个特定的数字
我的课本上有一个问题让我卡住了。问题是要确定将随机数相加到20(或更多)所需的数目。 我在这种情况下使用循环。我不确定下面的代码MATLAB:添加向量元素,直到达到一个特定的数字,matlab,loops,Matlab,Loops,我的课本上有一个问题让我卡住了。问题是要确定将随机数相加到20(或更多)所需的数目。 我在这种情况下使用循环。我不确定下面的代码 a=rand(1000,1) count =1 for(a=rand(1000,1)) count = count + 1 sum(a((count),1)) if sum(a(count),1)>20 break end end 我要做的是将向量中的元素相加,直到它达到20个或更多。此选项使用低内存 a = ran
a=rand(1000,1)
count =1
for(a=rand(1000,1))
count = count + 1
sum(a((count),1))
if sum(a(count),1)>20
break
end
end
我要做的是将向量中的元素相加,直到它达到20个或更多。此选项使用低内存
a = rand(1000,1);
Limit = 20;
Acu = 0;
N = 1;
while Acu < Limit
Acu = Acu + a(N, 1);
N = N +1;
end
disp(N-1);
a=rand(1000,1);
限值=20;
Acu=0;
N=1;
而Acu<极限
Acu=Acu+a(N,1);
N=N+1;
结束
disp(N-1);
在MATLAB中,一个简单的方法是创建一个足够长的随机列表,其总和远远大于您的限制,然后在其上运行cumsum
函数对向量进行累积总和,然后根据总和向量中的值选择原始随机向量的最低元素
limit = 20;
randnums = rand(1, limit*10); % Create a sufficiently long vector of random numbers
sumnums = cumsum(randnums); % Compute the cumulative sum of the random vector
limitedrandnums = randnums(sumnums<=limit); % Select the values from the random vector based on the sum
disp(limitedrandnums);
disp(sum(limitedrandnums));
limit=20;
randnums=rand(1,极限*10);%创建一个足够长的随机数向量
sumnums=cumsum(randnums);%计算随机向量的累积和
limitedrandnums=randnums(sumnums1)使用forcount=1:numel(a)
并删除count=行,2)使用sum(a(1:count))
应该可以工作。最后一行应该是disp(N-1)
。