Can not get row vector to be 1,5

5 ビュー (過去 30 日間)
Dylan Blosser
Dylan Blosser 2019 年 11 月 25 日
コメント済み: Ridwan Alam 2019 年 11 月 28 日
I have written code to generate random numbers within a constrant and I just want the end result to be a row vector of 5 different times, not 6 different vectors adding one until it reaches 1,6. What do I need to change?
n=0;
for a=89:0.5:91.5;
n=n+1;
V(n)=2*rand+a
end

回答 (2 件)

Adam Danz
Adam Danz 2019 年 11 月 25 日
編集済み: Adam Danz 2019 年 11 月 25 日
First, here's the correct way to set up the loop. Avoid the n=n+1 approach in for-loops because for-loops are designed to iterate that way.
a = 89:0.5:91.5;
V = nan(size(a));
for i = 1:numel(a)
V(i)=2*rand+a(i);
end
Or, better yet, the vectorized version that does the entire thing in 1 line
V = 2 * rand(size(a)) + a;
But since 'a' contains 6 values, V will also contain 6 values. If you want 5 values, you'll need to redefine a.

Ridwan Alam
Ridwan Alam 2019 年 11 月 25 日
Because a=89:0.5:91.5 gives you a vector of length 6
n=0;
V = [];
for a=89:0.5:91
n=n+1;
V(n)=2*rand+a
end
  1 件のコメント
Ridwan Alam
Ridwan Alam 2019 年 11 月 28 日
Hi Dylan, please accept the response as an answer if it works. Thanks!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLinear Algebra についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by