MATLAB: Converting input matrix A with size 4×3 into B matrix with size 12×3 with coordinates in matrix A

MATLABmatrix arraymatrix manipulation

Hello!
So i have this input matrix A with size that varies but for example let's asume size is 4×3.
where
A=[a11 a12 a13;
a21 a22 a23;
a31 a32 a33;
a41 a42 a43]
and want to form another matrix B with the respective coordinates in the matrix for rows and columns and the value itself, resulting in a 12×3 matrix.
So in my case i want B= i j aij for all rows for all aij values in matrix A
B=[1 1 a11;
1 2 a12;
1 3 a13;
2 1 a21;
2 2 a22;
2 3 a23;
3 1 a31;
3 2 a32;
3 3 a33;
4 1 a41;
4 2 a42;
4 3 a43]
So one row of B has 3 values: Horizontal coordinate in number of columns, Vertical coordinate in number of rows and the last value is ithe value itself located at those coordinates
I've done the task in excel with index function but the txt input and large format of input matrix (can reach 10000×10000) and the variating size of the input data makes much more sense to do this in matlab.
I'm very new to matlab and need a bit of help if possible. Thank you!

Best Answer

There are some slicker ways to do this, but it might be instructive for you to see how to do this with a simple for loop:
[m,n] = size(A);
B = zeros(m*n,3);
for nr = 1:m
for nc = 1:n
B(n*(nr-1)+nc,:) = [nr nc A(nr,nc)];
end
end
Related Question