MATLAB: Vectorization, avoiding loops

MATLABvectorization

Hello!
I have a Matrix, A=rand(9,10)
Now, I want to add a new number, to a new row, for every column b=[2,3,4;7 1 6];
I can do this using loops but I want to use Vectorization for speed.
A ( end +1 , b(1) ) = 1
A ( end +1 , b(2) ) = 1
A ( end +1 , b(3) ) = 1
Thank you 🙂

Best Answer

Assuming this:
b=[2,3,4;7 1 6];
is a typo and supposed to read:
b=[2,3,4,7,1,6];
Then you can make the new rows as a matrix of zeros, set appropriate elements = 1, then concatenate:
A = rand(9, 10)
b=[2,3,4,7,1,6];
%make the new rows as a single block
newRows = zeros(length(b), size(A, 2));
bIx = sub2ind(size(newRows), 1:length(b), b);
newRows(bIx) = 1;
%concatenate them
A = [A; newRows]
Example output:
A =
0.5470 0.0811 0.8176 0.5502 0.2259 0.9797 0.2217 0.0292 0.5211 0.8852
0.2963 0.9294 0.7948 0.6225 0.1707 0.4389 0.1174 0.9289 0.2316 0.9133
0.7447 0.7757 0.6443 0.5870 0.2277 0.1111 0.2967 0.7303 0.4889 0.7962
0.1890 0.4868 0.3786 0.2077 0.4357 0.2581 0.3188 0.4886 0.6241 0.0987
0.6868 0.4359 0.8116 0.3012 0.3111 0.4087 0.4242 0.5785 0.6791 0.2619
0.1835 0.4468 0.5328 0.4709 0.9234 0.5949 0.5079 0.2373 0.3955 0.3354
0.3685 0.3063 0.3507 0.2305 0.4302 0.2622 0.0855 0.4588 0.3674 0.6797
0.6256 0.5085 0.9390 0.8443 0.1848 0.6028 0.2625 0.9631 0.9880 0.1366
0.7802 0.5108 0.8759 0.1948 0.9049 0.7112 0.8010 0.5468 0.0377 0.7212
A =
0.5470 0.0811 0.8176 0.5502 0.2259 0.9797 0.2217 0.0292 0.5211 0.8852
0.2963 0.9294 0.7948 0.6225 0.1707 0.4389 0.1174 0.9289 0.2316 0.9133
0.7447 0.7757 0.6443 0.5870 0.2277 0.1111 0.2967 0.7303 0.4889 0.7962
0.1890 0.4868 0.3786 0.2077 0.4357 0.2581 0.3188 0.4886 0.6241 0.0987
0.6868 0.4359 0.8116 0.3012 0.3111 0.4087 0.4242 0.5785 0.6791 0.2619
0.1835 0.4468 0.5328 0.4709 0.9234 0.5949 0.5079 0.2373 0.3955 0.3354
0.3685 0.3063 0.3507 0.2305 0.4302 0.2622 0.0855 0.4588 0.3674 0.6797
0.6256 0.5085 0.9390 0.8443 0.1848 0.6028 0.2625 0.9631 0.9880 0.1366
0.7802 0.5108 0.8759 0.1948 0.9049 0.7112 0.8010 0.5468 0.0377 0.7212
0 1.0000 0 0 0 0 0 0 0 0
0 0 1.0000 0 0 0 0 0 0 0
0 0 0 1.0000 0 0 0 0 0 0
0 0 0 0 0 0 1.0000 0 0 0
1.0000 0 0 0 0 0 0 0 0 0
0 0 0 0 0 1.0000 0 0 0 0