## Spaces for readability in code

### K E (view profile)

on 8 Nov 2012
Which of following lines of code do you think is more readable:
plot(rand(1,1,1)+17/2,'r*');%No spaces
plot(rand(1, 1, 1) + 17/2, 'r*') ; % Space after commas, around arithmetic, before semicolons
I code with convention #2, which feels closer to the spacing of written text, but #1 seems to be more standard among Matlab programmers.
EDIT: Too much space is hard to parse, so I am going stop leaving space before commas. Personal preference seems to be the rule. Thanks everyone.
plot(rand(1,1,1) + 17/2, 'r*') ;

John Petersen

### John Petersen (view profile)

on 8 Nov 2012
I mostly use a combination of that where I condense with commas, but use more spacing for arithmetic, e.g.
plot(rand(1,1,1) + 17/2, 'r*')
Evan

### Evan (view profile)

on 8 Nov 2012
I generally don't put spaces between commas, semicolons, colons and parenthesis. I use spaces for arithmetic (except for exponents, for some reason :P) and logical operators. For some reason I've always found code with no spaces after equals signs, addition, etc. to be messy and hard to read.
So I would type your example like this:
plot(rand(1,1,1) + 17/2,'r*');
EDIT: I would say I prefer your convention #2 over #1.

### Daniel Shub (view profile)

on 9 Nov 2012

I recently found out that spacing can matter. I generally go with no spaces between operators, but always spaces after commas and surrounding equal signs
plot(rand(1, 1, 1)+17/2, 'r*')
A = (rand(1, 5)-3)+bsxfun(@(x, y)x+y, Z, U)-cellfun('length', M{:})
At one point I thought that it might be cleaner to do
A = minus(plus(minus(rand(1, 5), 3), bsxfun(@(x, y)plus(x, y), Z, U)), cellfun('length', M{:}))
but that was a short lived experiment.

### Sean de Wolski (view profile)

on 8 Nov 2012
Edited by Sean de Wolski

### Sean de Wolski (view profile)

on 8 Nov 2012

#
My eyes don't like having to parse an entire monitor. Though I do like spaces and commas in concatenations:
function [x, y, z] = foo(Q)
x = [Q, Q, Q];
y = ismember(Q,pi);
z = 17+5;
end

K E

### K E (view profile)

on 9 Nov 2012
Good point. #2 is too spread out.

### Matt Fig (view profile)

on 8 Nov 2012
Edited by Matt Fig

### Matt Fig (view profile)

on 8 Nov 2012

Here is how I do it:
plot(rand(1,1,1) + 17/2,'r*')
A = (rand(1,5) - 3) + bsxfun(@(x,y) x+y,Z,U) - cellfun('length',M{:})
No spaces around commas, spaces B&A: =+-*/ unless the operands are easily seen by my eye and not between paranthesis or function calls. So for example, the two operands to the plus are not easily picked out, so I put a space B&A. The operands to the division are, so no space. Commas stick out like sore thumbs to me, so I never space them or semicolons.
Yep, I make my own spacing rules and I like them!