I want to optimize some examples by omitting an unnecessary loop but I don't know how. Here are the examples:
%Subtract 7 from all elements on the matrix diagonal
A=rand(100,100)*10;
for i=1:100
A(i,i)=A(i,i)-7;
end
---
%Count the number of elements of matrix A which are bigger than the adequate elements of matrix B
A=rand(100,100)*10;
B=rand(100,100)*10;
a_bigger=0;
for i=1:100
for j=1:100
if A(i,j)>B(i,j)
a_bigger=a_bigger+1;
end
end
end
---
%Create vector with sums of 100 natural numbers (so-called cumulative ``sum):
B=[1, 1+2, 1+2+3... 1+2+3+...+n]
A=1:100;
B=zeros(1,100);
for i=1:100
for j=1:i
B(i)=B(i)+A(j);
end
end
I tried to solve the first one with
n=100;
A=rand(n,n)*10;
x=ones(1,n)*7;
diag(x);
A=A-x;
However, it was worse than as it is. It required more time to run the code. Why is this? Is there a faster way to implement this?
I was looking at the vectorization page and I tried to use the find
function to solve the second one. But when i wrote the code
A=rand(100,100)*10;
B=rand(100,100)*10;
a_bigger=0;
find(A);
find(B);
if find(A)>find(B)
a_bigger = a_bigger + 1;
end
a_bigger
it gives me 0 as a result. What am I doing wrong?