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

1 view (last 30 days)
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 Comments
Sophie Culhane
Sophie Culhane on 8 Oct 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 on 8 Oct 2020
I also added 'number = number + 1;' after 'A(row,col) = A(row,col) + number;' in both areas.

Sign in to comment.

Accepted Answer

Ameer Hamza
Ameer Hamza on 7 Oct 2020
Edited: Ameer Hamza on 7 Oct 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 Comments

Sign in to comment.

More Answers (0)

Categories

Find more on Line Plots in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!