MATLAB Function Takes as Input Two Positive Integers and Returns a Matrix

4 visualizaciones (últimos 30 días)
Write a MATLAB function that takes as input two positive integers and returns a matrix. Given positive integers m and n, hw21 creates an m x n array A whose elements consist of the first mn positive integers stored in A as follows: the first column of A consists of the first m consecutive positive integers given in order from 'top to bottom', the second column of A (if it exists) consists of the next m consecutive positive integers given in order from 'bottom to top', and continues filling in the columns in order with the next m consecutive positive integers by alternating between 'top to bottom' and 'bottom to top' until all columns are filled in.
So far I have a small program written but I stuck with what to do next. I dont know what to put in 'A = ?', so I am asking for assistance on how to get started. Heres what I have:
function A = hw21(m,n)
%
[NRows, NCols] = size(A);
number = 0
for col = 1:NCols
for row = NRows:1
A = ?;
number = number + 1;
end
end
  2 comentarios
Sophie Culhane
Sophie Culhane el 8 de Oct. de 2020
I now have this program which is more developed, but still does not work. Any ideas on how to progress?
function A = hw21(m,n)
%
NRows = m;
NCols = n;
A = zeros(NRows, NCols)
number = 0;
for col = 1:NCols
number = number + 1;
even = fix(col/2);
if even == col/2
for row = NRows:1:1
A(row,col) = A(row,col) + number;
end
else
for row = 1:NRows
A(row,col) = A(row,col) + number;
end
end
end
Sophie Culhane
Sophie Culhane el 8 de Oct. de 2020
I also added 'number = number + 1;' after 'A(row,col) = A(row,col) + number;' in both areas.

Iniciar sesión para comentar.

Respuesta aceptada

Ameer Hamza
Ameer Hamza el 7 de Oct. de 2020
Editada: Ameer Hamza el 7 de Oct. de 2020
Since this is a homework problem so I won't give you a direct solution but following will give you hints.
You need to have a different order of elements for even and odd columns. To check if the current value of col is even or odd, see the rem() function. Then you can write two for-loops for even and odd column.
Also, use row and cols as indexes of matrix A.
Here is a general sketch.
function A = hw21(m,n)
%
[NRows, NCols] = size(A);
number = 0
for col = 1:NCols
number = number + 1;
iseven = rem(col, ???) % check if if it is even or odd
if iseven
for row = NRows:1
A(row, col) = ?; % think what should you assign here at this row and col position
end
else
for row = 1:NRows
A(row, col) = ?; % think what should you assign here at this row and col position
end
end
end
  3 comentarios
Ameer Hamza
Ameer Hamza el 8 de Oct. de 2020
Here is another test for even
iseven = floor(col/2)==col/2;

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Logical en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by