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

조회 수: 12 (최근 30일)
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
Sophie Culhane
Sophie Culhane 2020년 10월 8일
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 2020년 10월 8일
I also added 'number = number + 1;' after 'A(row,col) = A(row,col) + number;' in both areas.

댓글을 달려면 로그인하십시오.

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 10월 7일
편집: Ameer Hamza 2020년 10월 7일
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
Ameer Hamza
Ameer Hamza 2020년 10월 8일
Here is another test for even
iseven = floor(col/2)==col/2;

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Line Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by