Converting input matrix A with size 4x3 into B matrix with size 12x3 with coordinates in matrix A

3 views (last 30 days)
Hello!
So i have this input matrix A with size that varies but for example let's asume size is 4x3.
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 12x3 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 10000x10000) 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!

Accepted Answer

the cyclist
the cyclist on 31 Mar 2020
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
  1 Comment
Adrian Asi
Adrian Asi on 31 Mar 2020
Thank you.
Similiar to what I've been trying but with lack of syntax for Matlab. At least I perfectly understand this one.
Works perfect.

Sign in to comment.

More Answers (1)

the cyclist
the cyclist on 31 Mar 2020
Here is a somewhat slick way:
[m,n] = size(A);
AA = A';
B = [repelem(1:m,n)' mod(0:m*n-1,n)'+1 AA(:)];
This is fine if one understands the underlying functions, but is pretty obfuscated if one doesn't. However, in limited testing, this version is about twice as fast.
  1 Comment
Adrian Asi
Adrian Asi on 31 Mar 2020
Very slick indeed. And very fast. I ended up using this one instead since some of the files are very large.
Tried on 1300x1300 matrix and was notacebly faster than the for loop.
Thank you a lot!

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!