Create a new matrix that includes consecutive numbers from another array

I am trying to create a matrix n x 5. The matrix will be built from another array that includes integers.

All lines begin with a number minus 4 and end with a number from an array. I am trying to find an effective method that does not use for-loop. To illustrate the situation, I will give an example:

b=[6 8 9 11 13 16 17 ];
A=zeros(length(b),5);

After using the code I want to get:

A=[2:6;
   4:8;
   5:9;
   9:13;
   12:16;
   13:17];
+4
source share
1 answer

bsxfun @plus @minus b , -4 to 0 @plus 4 to 0 @minus specifier . , :

bsxfun(@plus,b(:),-4:0)
bsxfun(@minus,b(:),4:-1:0)

-

>> b
b =
     6     8     9    11    13    16    17
>> bsxfun(@plus,b(:),-4:0)
ans =
     2     3     4     5     6
     4     5     6     7     8
     5     6     7     8     9
     7     8     9    10    11
     9    10    11    12    13
    12    13    14    15    16
    13    14    15    16    17
>> bsxfun(@minus,b(:),4:-1:0)
ans =
     2     3     4     5     6
     4     5     6     7     8
     5     6     7     8     9
     7     8     9    10    11
     9    10    11    12    13
    12    13    14    15    16
    13    14    15    16    17
+5

Source: https://habr.com/ru/post/1611433/


All Articles