In: Advanced Math
Write a function called alternate that takes two positive integers, n and m, as input arguments (the function does not have to check the format of the input) and returns one matrix as an output argument. Each element of the n-by-m output matrix for which the sum of its indices is even is 1. All other elements are zero. For example, here is an example run:
>> alternate(4,5)
ans =
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
Once again, using the zeros function can help, but it is not necessary
If you have any queries let me know through the comments.
I have given the code for your requirements.
Of course I have executed the code snippet with the random values and it give the as expected output. I am attaching output screenshots with this answer.
To get the proper execution you need to do as follows
Just place this body of the function code snippet in the function header alternate(n,m) and save the file name as alternate.m
Function Header :
function matrix = alternate(n,m)
% This function prints the alternate matrix.
Now load the alternate.m file into the workspace then execute the command
>> alternate(4,5)
You will definately get the output.
Body of the function :-
A = [ ];
for i=1:n
for j=1:m
x=i+j; % The sum of
indices
if mod(x,2)==0 % To check the sum of
indices are even or odd.
A(i,j)=1; % For
even indices the valu is 1
else
A(i,j)=0; % For odd indices the valu is 0
end
end
end
disp(A); % To display the alternate matrix.
Sample output :
If you have any queries let me know through the comments.
If you have any queries let me know through the comments.
Thank You.