Problem 11. Back and Forth Rows
Given a number n, create an n-by-n matrix in which the integers from 1 to n^2 wind back and forth along the rows as shown in the examples below.
Examples:
Input n = 3 Output a = [ 1 2 3 6 5 4 7 8 9 ]
Input n = 4 Output a = [ 1 2 3 4 8 7 6 5 9 10 11 12 16 15 14 13 ]
Solution Stats
Problem Comments
-
16 Comments
nice one
good one
i got same solution on matlab, but i don't know why i didn't here
I am no expert, but does anyone else think that the first test case is flawed? "%%n = 4;" instead of " %% (new line) n = 4;" So, "n" is never defined for the first case. Am I right? If not, I apologize!
that seems legit
nice one
Really enjoyed this one.
Can someone help me? My solution works on my matlab but gives me an error during the test! What am I supposed to do ? :(
I think the answer to test suite 5 should be c = 2 since the first row is 0.21 and the second is 0.26. Please correct me if I'm wrong.
Awesome!
Awesome
Great
Check this out.
function b = back_and_forth(n)
b=1:n^2;
b=reshape(b,n,n)';
for i=2:2:n
b(i,:)=fliplr(b(i,:));
end
end
It appears a '\r' is needed after the %% in the first test of the solution to make it process properly.
The problem with the first test case has been fixed here.
This code
b=vec2mat(1:n^2,n)
b(2:2:end,:)=fliplr(b(2:2:end,:))
work in Matlab, why it doesn't works on site?
Solution Comments
Show commentsProblem Recent Solvers6830
Suggested Problems
-
2584 Solvers
-
1221 Solvers
-
282 Solvers
-
368 Solvers
-
Create an n-by-n null matrix and fill with ones certain positions
602 Solvers
More from this Author96
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!