2. (22%) Convert the following pieces of code in just a single line of code. In
ID: 2291306 • Letter: 2
Question
2. (22%) 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
_________________________________
Explanation / Answer
Consider B
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
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);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.