0
votes

I have the following question:

Write a program that:

  1. Starts by requesting an A matrix by keyboard.

  2. Next, if the number of columns of A is odd, the last column of additional zeros must be added. From this moment matrix, A has an even number (n) of columns.

The program will divide the input matrix into two sub-matrices.

  1. The first sub-matrix (A1) contains the first n / 2 columns of A. The second sub-matrix (A2) has the last n / 2 columns.

  2. Finally, the program must calculate and write on the screen a matrix B that has the rows of A1 in the odd rows and those of A2 in the pairs.

Example code

A = input('Enter a matrix:')
% A = magic(5) % for example
[filA, colA] = size(A);

if rem(colA,2)==1
    A = [A, zeros(filA,1)]
    colA = colA + 1;
end

A1 = A(:, [1:colA/2])
A2 = A(:, [1+(colA/2):colA])

%B
2
..and the question is how to outsource "homework"? Or ...where did I hide the errorcode and effort in resolving it? Restructure your question if its not homework.. it reads like it and implement the error your code produces and structure your question around the problem.ZF007
Please clarify your question. What is the problem with your code? Is there an error? What do you expect to get from posting your code here?Cris Luengo
I do not know how to use the if statement to create the matrix B, taking the rows of matrices A1 and A2 alternately. That's what the code lacks. ThanksOromion
Now I have tried to restructure the problem, making emphasis in step 4, in the first version I had tried to give my solution to step 4, but I did not know how to handle rows of each matrix to be able to concatenate in my matrix B.Oromion
There is no branching here (if statements). What have you actually attempted?Mad Physicist

2 Answers

1
votes

Here is the solution I propose you:

A = [1 2 3; 1 2 3; 1 2 3; 1 2 3];
[A_r,A_c] = size(A);

if (mod(A_c,2) ~= 0)
    A = [A zeros(A_r,1)];
    A_c = A_c + 1;
end

off = A_c / 2;
A1 = A(:,1:off);
A2 = A(:,(off+1):A_c);

B = reshape([A1(:) A2(:)].',2*A_r,[])

It makes use of the reshape function for interleaving the rows of the matrices A1 and A2. By omitting the ; at the end of the last line, you let Matlab print the output of the final computation in the console, which is:

B =
     1     2
     3     0
     1     2
     3     0
     1     2
     3     0
     1     2
     3     0

Using a step by step debugging approach, you can see how every step is being performed.

0
votes

My solution

clear all, clc;
A = input('Ingrese una matriz:')
[filA, colA] = size(A);
if rem(colA,2)==1
    A = [A, zeros(filA,1)]
    colA = colA + 1;
end

A1 = A(:, [1:colA/2])
A2 = A(:, [1+(colA/2):colA])

B = A2([1;1]*(1:size(A2,1)),:)
B(1:2:end,:) = A1