How do I create an array with unequal increment?

1 回表示 (過去 30 日間)
Wing
Wing 2018 年 2 月 14 日
コメント済み: Wing 2018 年 2 月 15 日
I want to design a program to create an array of numbers. The user can input the maximum and minimum values and the scaling factor.
For example,
max=256,
min=2,
scaling factor=2.
The array will be [2 4 8 16 32 64 128 256].
Is there anyway I can create such array with the max, min and scaling factor as variables? I tried doing it with the following code. However, the x(count) only gives me 1 number instead of storing the answers from the loop.
Is this the right direction to do it? Or is there any other codes to do it in a more efficient way?
Thanks!
xmax=256;
xmin=2;
xfact=2;
count=0;
x=0;
if x<=xmax
count=count+1;
x(count)=x*xfact;
end

採用された回答

Star Strider
Star Strider 2018 年 2 月 14 日
Try this:
expspace = @(vmin,vmax,inc) vmin * inc.^(0:( log(vmax/vmin)/log(inc)));
vmin = 2;
vmax = 256;
inc = 2;
v = expspace(vmin, vmax, inc)
v =
2 4 8 16 32 64 128 256
It is also robust to other combinations of input arguments.

その他の回答 (1 件)

Birdman
Birdman 2018 年 2 月 14 日
a=2;%min
n=8;%max
r=2;%scaling factor
s = a*r.^(0:n-1)
  4 件のコメント
Stephen23
Stephen23 2018 年 2 月 15 日
編集済み: Stephen23 2018 年 2 月 15 日
"In the code you gave me, the input of maximum value is 8 instead of 265."
The last value is a*r.^(n-1), where a=2, r=2, and n=8, giving 2*2.^(8-1), which is equal to 2^8, which gives 256 (and is exactly what you requested in your question).
Wing
Wing 2018 年 2 月 15 日
Yes, but I would like the last element to be what the input is. so the input of the max number is = the last element. I understand what you mean but the max number that is input into the program might not necessarily be 2^i. For example, min=2, max=199, scaling factor=3, and I want the array to contain the numbers of 2*3, 2*3*3, 2*3*3*3, etc. Sorry for the confusion.

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

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by