Matlab - if, while, for
>> v = zeros(10,1)
v =
0
0
0
0
0
0
0
0
0
0
>> for i=1:10,
v(i) = 2^i;
end;
>> v
v =
2
4
8
16
32
64
128
256
512
1024
>> indices=1:10;
>> indices
indices =
1 2 3 4 5 6 7 8 9 10
>> for i = indices,
disp(i);
end;
1
2
3
4
5
6
7
8
9
10
>> v
v =
2
4
8
16
32
64
128
256
512
1024
>> i = 1;
>> while i <=5,
v(i) = 100;
i = i +1;
end;
>> v
v =
100
100
100
100
100
64
128
256
512
1024
>> i = 1;
>>
>> while true,
v(i) = 999;
i = i+1;
if i == 6,
break;
end;
end;
>> v
v =
999
999
999
999
999
64
128
256
512
1024
>> v(1) = 2;
>> if v(1) == 1,
disp('The Value is one');
elseif v(1) == 2,
disp('The value is two');
else
disp('The value is not one or two.');
end;
The value is two
>> load('plot and computing.mat')
>> [a,b] = squareAndCubeThisNumber(5)
a =
25
b =
125
>> X = [1 1; 1 2; 1 3];
>> X
X =
1 1
1 2
1 3
>> y = [1; 2; 3]
y =
1
2
3
>> theta = [0;1];
>> j = costFunctionJ(X,y,theta)
j =
0
>> theta = [0;0]
theta =
0
0
>> j = costFunctionJ(X,y,theta)
j =
2.3333
functionJ = costFunctionJ(X, y, theta)
% X is the 'design matrix' containing our training examples.
% y is the class labels
m = size(X, 1); % number of training examples
predictions = X * theta; % predictions of hypothesis on all m
sqrErrors = (predictions - y ).^2; % square errors
J = 1/(2*m) * sum(sqrErrors);