Repeating a task for each row without loop

7 ビュー (過去 30 日間)
Jonathan Pelletier-Marcotte
Jonathan Pelletier-Marcotte 2018 年 3 月 27 日
I'd like to do this expression without a loop,
x = [1, 1; 2, 2; 3, 3; 4, 7; 8, 8; 9, 9; 10, 15; 16, 16; 17, 17];
for i = 1:size(x,1)
y(i,1) = {[x(i,1):x(i,2)]}
end
Thanks in advance,
  4 件のコメント
Bob Thompson
Bob Thompson 2018 年 3 月 27 日
Ok. I personally don't know of a way to conduct a specific operation for each row of a matrix without defining a loop to run through the rows. It might be possible with some fancy indexing, but I don't know how.
Jonathan Pelletier-Marcotte
Jonathan Pelletier-Marcotte 2018 年 3 月 27 日
No problem,
Thank you Bob

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

採用された回答

Jan
Jan 2018 年 3 月 27 日
編集済み: Jan 2018 年 3 月 27 日
Instead of avoiding the loop, start with a clean version with pre-allocation:
x = [1, 1; 2, 2; 3, 3; 4, 7; 8, 8; 9, 9; 10, 15; 16, 16; 17, 17];
n = size(x, 1);
y = cell(n, 1);
for k = 1:n
y{k} = x(k,1):x(k,2);
end
This has several improvements:
  • With a pre-allocation before the loop, the array does not grow iteratively. Remember that creating an array iteratively, Matlab has to create a new array and copy the old contents in each iteration. For a 1xN array this needs to reserve memory for sum(1:N) elements and this is growing extremely fast.
  • y(i,1) = {...} creates a cell on the right side only to copy its elements to the left side. The creation of the temporary cell can be saved by using the curly braces on the left side: y{i,1} = ...
  • a:b is a vector already. Including it in square brackets concatenates it with nothing. Therefore [a:b] is a waste of time. See Avoid square brackets .
  • The link about brackets might be useful: Are you sure that storing the index vectors explicitly is useful? Remember that:
y = x(a:b);
is faster than:
v = a:b;
y = x(v);
So maybe your Nx2 matrix is the best way to store the indices already. Then searching for a vectorized way to convert it might be a bad idea in general.
  1 件のコメント
Jonathan Pelletier-Marcotte
Jonathan Pelletier-Marcotte 2018 年 3 月 27 日
Very clear answer, thank you!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by