How to have my array continuously expanding in a for loop?

87 ビュー (過去 30 日間)
David Stolnis
David Stolnis 2017 年 2 月 14 日
回答済み: Jan 2017 年 2 月 14 日
I have a 3x2 matrix (M). Column one is a starting location (mile markers) and column two is the ending location for that row. I want to create an array that will take every 0.1 increment between the start and end, put it in an array, and move on to the next row, BUT continue to add the elements to array instead of simply updating the array with latest span. Please see my example code below:
M = [1.0 1.5; 2.0 2.3; 1.7 2.2];
stop=length(M);
n=1;
for n = 1:stop
stuck = M(n,1):0.1:M(n,2)
end
The result is the 0.1 increment span of the last row: M = [1.7 1.8 1.9 2.0 2.1 2.2]
What I want is M = [1.0 1.1 1.2 1.3 1.4 1.5 2.0 2.1 2.2 2.3 1.7 1.8 1.9 2.0 2.1 2.2]
I have spent way too much time on this snag and any input would be appreciated!

採用された回答

Geoff Hayes
Geoff Hayes 2017 年 2 月 14 日
David - try concatenating using the square brackets
stuck = [];
M = [1.0 1.5; 2.0 2.3; 1.7 2.2];
stop=length(M);
n=1;
for n = 1:stop
stuck = [stuck M(n,1):0.1:M(n,2)];
end
  2 件のコメント
David Stolnis
David Stolnis 2017 年 2 月 14 日
Geoff, thank you, you're the man! I had seen this on similar post but I could not figure out how to use it in my instance. I completely see what it is doing now and this will greatly help me in the future. Much appreciated!
Jan
Jan 2017 年 2 月 14 日
編集済み: Jan 2017 年 2 月 14 日
For a large number of chunks the iterative growing will require a lot of resources. Then creating a cell at first is more efficient.

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

その他の回答 (2 件)

Adam
Adam 2017 年 2 月 14 日
編集済み: Adam 2017 年 2 月 14 日
You'll have to use a cell array since they will be of different lengths for each row e.g.
stuck{n} = M(n,1):0.1:M(n,2);
As an aside, don't use
length( M )
use
size( M, 1 )
instead. It is safer. Maybe you will never have a case where you only have 1 row, but if you do length will return 2 because it just gives you the longest dimension. size( M, 1 ) will always explicitly give you the number of rows.
  1 件のコメント
David Stolnis
David Stolnis 2017 年 2 月 14 日
Thank you. It seems Geoff below has a better solution allowing me to keep my array as a double. But thank you for the input on the size function. I'll be using that from now on!

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


Jan
Jan 2017 年 2 月 14 日

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by