Matlab matrix element not being reassigned?

35 Views Asked by At

I am attempting to create a function in Matlab which turns all matrix elements in a matrix to '0' if the element is not symmetrical. However, the element appears to not be reassigning.

function [output_ting] = maker(a)

[i,j] = size(a);

if i ~= j
    disp('improper input!')
else
end
c = 1;
b = a.';
while c < length(a) + 1
    if a(c) == b(c)
        c = c + 1;
        continue
    else
        a(c) = 0;
        c = c + 1;
    end
end
disp(a)
end
2

There are 2 best solutions below

0
On

while c < length(a) + 1

$a$ is a matrix, a 2D structure. You appear to want to use 1D indexing, but the length is giving you the number of rows. Use length(a(:)), or numel(a).

1
On

Firstly, a word of caution: I use Octave to test my code. Please check if my code works for you as well.

In general, I dislike the use of explicit looping and mutation. They looks too primitive to me. I believe that programming should be done in a high-level way. But of course, this is just my taste. In this case, there is a simple way to do what you want. Consider the following function:

function B = symmetrize(A)
  %{ die if A is not a square matrix  %}
  if ~issquare(A)
    error('improper input!');
  end

  B = A; % make a copy of A
  B(find(A - A.')) = 0; % set all the non-symmetric entries to 0
end

To test it:

  1. Copy the code into symmetrize.m.
  2. Type A = [1 0 1; 1 1 1; 1 0 1] to define the matrix $A$.
  3. Type B = symmetrize(A) to define the matrix $B$ which is the matrix you want.

Feel free to ask if you don't understand something.