In: Electrical Engineering
Convert the following pieces of code in just a single line of code. In all cases, A and B are arrays of size 5 x 5. Important: The expression "single line of code" implies a single command or equality. In other words, the code: X=A+1; X=X+B; is considered to be TWO lines.
(a) (4%) for i=1:5,
for j=1:5
A(i,j)=B(i,j)+1;
end
end
_________________________________
(b) (4%) for i=1:3
for j=2:4
A(i,j)=B(i,j);
end
end
_________________________
(c) (5%) for i=1:3
for j=2:4
A(i,j)=B(i+2,j+1);
end
end
_________________________________
(d) (4%) for i=1:5
for j=1:5
A(i,j)=1/(B(i,j))^2;
end
end
_________________________________
(e) (5%) for i=1:5
for j=1:5
A(i,j)=B(6-i,j);
end
end
_________________________________
Consider B
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
for i=1:5
for j=1:5
A(i,j)=B(i,j)+1;
end
end
Above code can be replaced by single line using
A = B+1; %each element of A is populated from corresponding element of B by adding 1
>> A
A =
18 25 2 9 16
24 6 8 15 17
5 7 14 21 23
11 13 20 22 4
12 19 26 3 10
>> B
B =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
>> B+1
ans =
18 25 2 9 16
24 6 8 15 17
5 7 14 21 23
11 13 20 22 4
12 19 26 3 10
for i=1:3
for j=2:4
A(i,j)=B(i,j);
end
end
Can be replaced by
A(1:3,2:4) = B(1:3,2:4)
for i=1:3
for j=2:4
A(i,j)=B(i+2,j+1);
end
end
can be replaced by A(1:3,2:4)=B(3:5,3:5);
part d
for i=1:5
for j=1:5
A(i,j)=1/(B(i,j))^2;
end
end
Can be replaced by A = 1./(B.^2)
for i=1:5
for j=1:5
A(i,j)=B(6-i,j);
end
end
can be replaced by
A(1:5,1:5) = B(5:1,5:1);