MATLAB: Which way of programming is more efficient and faster

MATLAB

Dear friends,
I would like to know whether there is a difference between following cases. Your responses are appreciated.
Case 1
X = 1;
Y = X + 4;
Z = X + Y;
Case 2
X = 1; Y = X + 4; Z = X + Y;
Other cases that I want to compare are as follows:
Case 3
v1 = k1{t};
nVar = size(v1, 2);
CP = randsample(nVar-1, 2);
Case 4
CP = randsample(size(k1{t}, 2)-1, 2);

Best Answer

No, there is no difference between the cases. More importantly, even if there was, you shouldn't care until you've proven that the operations are a bottleneck.
If you haven't proven that the operations are a bottle neck (by using the profiler), then you should care about clarity, and for that reason, you should prefer case 1 over case 2. As for the other two cases, unless nVar and v1 are going to be reused later on, I'd prefer case 4 as there's little point in creating temporary variables that are only used once.
But again, considerations about speed shouldn't even be on your radar at this point.