Can this task be solved more efficiently?

61 Views Asked by At

The following task is to write a little program to make a $5\times 9$-matrix that consists of the elements from 1 till 9 for each row. However each row has the power $+1$ of the previous row untill the $power = 5$ . So,

$$\begin{pmatrix} 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9\\ 1^2 & 2^2 & 3^2 & 4^2 & 5^2 & 6^2 & 7^2 & 8^2 & 9^2\\ 1^3 & 2^3 & 3^3 & 4^3 & 5^3 & 6^3 & 7^3 & 8^3 & 9^3\\ 1^4 & 2^4 & 3^4 & 4^4 & 5^4 & 6^4 & 7^4 & 8^4 & 9^4\\ 1^5 & 2^5 & 3^5 & 4^5 & 5^5 & 6^5 & 7^5 & 8^5 & 9^5\\ \end{pmatrix}$$

My approach was just to input the vector $\begin{bmatrix} 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 \end{bmatrix}$ of each row to the power that was needed and I felt like that was most efficient (by this I mean with the least amount of code) way to program it without using for, while or if- else-constructions. But I still think there is a more efficient way to do it directly without using the previously mentioned constructions.

Anyone any ideas?

2

There are 2 best solutions below

4
On BEST ANSWER

This depends on the language you're using, but you can at least improve things slightly, by computing the entries of row $k$ by taking those of row $k-1$ and multiplying them by $\pmatrix{1&2&3&4&5&6&7&8&9}$. This lets you compute the fifth row with just 9 multiplies, rather than $9 \cdot 4$ multiplies.

If multiplication is an expensive operation, then this is a win; then again, if fetching an entry of an array is an expensive operation, then it's not.

If you were doing to same thing for a $5000 \times 9$ matrix, I'd expect my method to be honestly more efficient: in each column, instead of doing a total of $4999 \cdot 50000/2$ multiplies, I'd do only $4999$. That would probably outweigh the cost of the $4999$ fetches, And as the number of rows grows larger, the number of multiples in the naive approach increases quadratically, while the number of fetches in the fancier approach increases only linearly, so for some matrix height, the fancy method will end up definitely being better.

3
On

You apparently want a matlab programming answer, so here goes:

[u,v] = ndgrid(1:5, 1:9); 
A = arrayfun(@(i,j)j^i, u, v); 

Is it more "efficient"? Without a clear description of what you might mean by "efficiency", that's unanswerable. It's certainly fewer characters of typing.