USING MATLAB 4 Create the following matrix a Preallocate by
USING MATLAB
4. Create the following matrix
a) Pre-allocate by setting all elements to zero. Use two sequential for-loops and no if-statements.
b) Pre-allocate by setting all elements to zero. Use two nested for-loops with an if-elseif-statement.
c) Pre-allocate by setting all diagonal elements to one. Use a while-loop with no if-statements.
| 1 | -2 | 0 | 0 |
| 0 | 1 | -2 | 0 |
| 0 | 0 | 1 | -2 |
| 0 | 0 | 0 | 1 |
Solution
a) M=[]
for i=1:4
for j=1:4
M[i-1][j-1]=0
end
end
c) M[0][0]=1
M[1][1]=1
M[2][2]=1
M[3][3]=1
i=0
j=0
while(i>j)
{
while(!j<=i)
if(j<i)M[i][j]=-2
end
j++;
end
j=0
i++
end
