필터 지우기
필터 지우기

nxm matrix function with zeros and ones

조회 수: 6 (최근 30일)
Lewis HC
Lewis HC 2023년 1월 10일
댓글: Lewis HC 2023년 1월 10일
Greetings everyone, I need to write a function called square that takes as input arguments two positive integer scalars n and m in that order, the function must create and return y, which is the matrix nxm of the figure with alternating zeros and ones, my code is next:
function y=square(n,m)
A=ones(n,m);
A(1:2:n)=0;
y=[A]
end
Thank you!
  댓글 수: 1
Cris LaPierre
Cris LaPierre 2023년 1월 10일
Adding this comment to show the output of the function you have written.
y=square(3,4)
y = 3×4
0 1 1 1 1 1 1 1 0 1 1 1
function y=square(n,m)
A=ones(n,m);
A(1:2:n)=0;
y=[A];
end

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

채택된 답변

Matt J
Matt J 2023년 1월 10일
Hint:
x=[1 0 1 0 1];
y=[ 0 1 0 1 0 1];
abs(x-y')
ans = 6×5
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
  댓글 수: 1
Lewis HC
Lewis HC 2023년 1월 10일
Thank you very much dear friend, you helped me a lot in my learning of Matlab, I hope to know as much as you do in the future, thank you!

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

추가 답변 (1개)

Cameron
Cameron 2023년 1월 10일
You probably want to name it something other than "square" which is already a MATLAB function. You're off to a good start though. I find it most useful to think of these problems in basic terms. For instance - what do I want to do here, and how would I tell someone in very basic terms to do this? I would think of looping through the columns of your array and doing a similar thing that you have done. However, you need to start your zeros at a different point for each column. You can use an if statement to achieve that.
n = 20;
m = 7;
A = ones(n,m); %initialize your array
for ColumnNumber = 1:m %loop through your columns
if rem(ColumnNumber,2) == 0 %check your remainder when you divide by 2. is it even or odd?
StartPt = 1;
else %if you do have a remainder, do this
StartPt = 2;
end
A(StartPt:2:n,ColumnNumber)=0;
end
  댓글 수: 1
Lewis HC
Lewis HC 2023년 1월 10일
You are correct dear friend, I tell you that that was the problem in my code, I changed the name of the function and I had a correct answer, thank you very much for your help!

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

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by