First, install wmctrl either from your distribution's package manager or get the source here. Next, download this perl script. The script has the following syntax: perl next_desktop.pl [up|down|left|right [# ]]
Inside the script, there are some other configuration variables for setting how many rows and columns to use. You may set them, but if you leave them alone, the script will try to guess your layout based on the number of workspaces you have. This should result in the desired behavior in most cases.
Now, when you want to change desktops, use this script instead of the built-in commands.