How to concatenate -x:x for x=0,1,2,3,..n without a loop?

2 ビュー (過去 30 日間)
ailbeildce
ailbeildce 2017 年 11 月 3 日
コメント済み: Walter Roberson 2017 年 11 月 4 日
Hi,
I want to populate a matrix with rows in the form of
0,-1,0,1,-2,-1,0,1,2,-3,-2,-1,0,1,2,3
0,-1,0,1,-2,-1,0,1,2,-3,-2,-1,0,1,2,3
0,-1,0,1,-2,-1,0,1,2,-3,-2,-1,0,1,2,3
... ie -x:x for multiple x values. After this, I will call a function on the whole matrix to convert these numbers to something else. eg takesquare(Matrix) will give the elementwise squares of 0,-1,0,1,...
1. How to concatenate -x:x for x=0,1,2,3,..n without a loop? With a loop, solution is trivial and super slow.
2. How can I call the takesquare with additional parameters? So the idea is adding different values to each row, ie takesquare(Matrix, [column vector=2,0,7,1,5,6..]). I know bsxfun can be used, but since the operations should be elementwise, I'll need to repmat the columnvector to all entries then. Is there a better/less memory occupying way?
Thanks!

採用された回答

Walter Roberson
Walter Roberson 2017 年 11 月 4 日
編集済み: Walter Roberson 2017 年 11 月 4 日
Constructing it as a vector is possible in theory.
The value range -N to +N is in the (N+1)'th group and is a vector of length (2*N+1). The total length of the vector to the end of the -N:+N group can be found to be (N+1)^2 . Therefore for any given position, M, floor(sqrt(M-1)-1) tells you how many complete N have been gone through, and M minus that gives you the relative position in progress:
Nb = floor(sqrt(M-1)-1);
value_at_M = M - (Nb+1).^2 - 1 + -(Nb+1);
For any given final N, Nf, you can run that vectorized:
M = 1 : (Nf+1).^2;
Nb = floor(sqrt(M-1)-1);
value_at_M = M - (Nb+1).^2 - 1 + -(Nb+1);
"2. How can I call the takesquare with additional parameters? So the idea is adding different values to each row"
You only have one row.
  2 件のコメント
ailbeildce
ailbeildce 2017 年 11 月 4 日
First of all, thanks for the answer. For the second one I should be more clear: I have 4 2D arrays of same size, I have a function fn(Arg1,Arg2,Arg3,Arg4). I want to elementwise call this function with these 4 arrays. In other words, Arg1 will be picked from first 2D array, Arg2 from 2nd and so on.
Walter Roberson
Walter Roberson 2017 年 11 月 4 日
arrayfun(@fn, FirstArray, SecondArray, ThirdArray, FourthArray)

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

その他の回答 (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