How do you use the else if commands to alter variables in matrices?

2 ビュー (過去 30 日間)
Matlabuser2000
Matlabuser2000 2012 年 4 月 1 日
The question below is directly the question i am having extreme difficuilty with. I have no idea how to use elese if commands to do this question, thats why it is hard ,. If it was just subtracying values from a table then it would be easy to do but it saids to use eleseif commands. So yeah . Good luck
Create a two dimensional array (matrix) of dimension 5 X 5 of zeros, using the zeros(r,c)
command. Next overwrite some of the zeros to reproduce the matrix shown below. Do this
by using nested loops and a if...elseif...else...end statement to assign the dierent
values to the table of numbers. When you have initialized the array elements print out your
matrix to check, it should look like the one below.
0 0 0 5 8
0 0 5 8 3
0 5 8 3 0
5 8 3 0 0
8 3 0 0 0
  1 件のコメント
Rahul
Rahul 2012 年 4 月 2 日
This looks like a homework question..

サインインしてコメントする。

回答 (2 件)

Kye Taylor
Kye Taylor 2012 年 4 月 2 日
It helps to realize that the sum of the indices is constant along anti-diagonals in a matrix (while the difference is constant along diagonals)... Therefore, how about
m = 5;
n = 5;
A = zeros(m,n);
for i = 1:m
for j = max(1,n-i):min(n,n+2-i)
if (i+j == 5)
A(i,j) = 5;
elseif (i+j == 6)
A(i,j) = 8;
else
A(i,j) = 3;
end
end
end
disp(A)

Andrei Bobrov
Andrei Bobrov 2012 年 4 月 2 日
n = 5
M = full(spdiags(ones(n,1)*[3 8 5],[-1 0 1],n,n))
out = M(:,end:-1:1)
OR
M = zeros(n)
M([n-1:n-1:n^2-2*n+1;2*n:n-1:n^2-1]) = [5; 3]*ones(1,n-1)
M(n:n-1:n^2-1) = 8

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by