0

Lets say I have an original mxn matrix like this:

1 2 3 4
5 6 7 8

For the purpose of my program, I then concatenate the rows into this new one dimensional matrix:

1 2 3 4 5 6 7 8

I know the mxn size of the original matrix. My question is, given a value's position in the new matrix, I need an algorithm to find its mxn position in the original matrix.

For example: Using the above matrices, 8 would have an original position of 2x4, 3 would have an original position of 1x3 and so on.

This is for a java program that I am writing, I tried using division and modulus and played around with it, but I couldn't come up with a good algorithm that works for all cases.

asked May 18, 2016 at 2:39

1 Answer 1

1

If A is the original two-dimensional matrix, B is the new one-dimensional matrix, m & n are height and width of B respectively, then given the position p of element a in A, the new [x,y] coordinates within B (given indices that are one-based) is

x = (p - 1) / n + 1
y = n + 1 - (p % n) 

With zero-based indices, this becomes easier, as you no longer have to adjust for the 1 offset.

x = p / n
y = n - p % n
answered May 18, 2016 at 2:50
2
  • Thank you! I'm working with 0 based but the end value has to be 1 based for the user. Commented May 18, 2016 at 3:38
  • I just sat down to finish up my code, I think there may be some confusion, I need the [x,y] coordinates within A(mxn) given position p of element in B (one dimensional) Commented May 18, 2016 at 4:04

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.