0
votes

I'm trying to write a function to classify a vector of numbers.

function [a]=classify(x)
i=length(x);
for j=1:1:i
  if(x(j)<0.5)
      a(j,j,:)='low';
  elseif(x(j)==0.5)
      a(j,1,:)='medium';
  else
      a(j,1,:)='high';
  end
end

When I tried the code, I get the Subscripted assignment dimension mismatch error.

classify([0.5 0.1])
Subscripted assignment dimension mismatch.

Error in classify (line 5)
 a(j,1,:)='low';

is the error due to the size of my matrix? I've look through other solutions but none of them seem to be working.

1
Assuming the second j in a(j,j,:)='low'; is a typo? - chappjc
ya, the second j is a typo, sorry about that - kenny

1 Answers

2
votes

The first time through your function, j = 1, so with the values in your input vector you end up assigning:

a(j,1,:)='medium';

You can check that:

>>size(a)
ans =
     1     1     6

The next time through your loop you have j = 2, and then assign:

a(j,j,:)='low';

But this causes the error because your array expects the new string assignment, along the 3rd dimension of your array, to also have length = 6 (the length of 'medium'), since that is the value you used to initialize your array.

Your array sees this as an incompatible assignment, giving the error.

To get around this you will need to use something like a Cell array, which can accommodate variable data sizes and even types.

So your code will need to look something like this (note the change from () to {} for the array):

function [a]=classify(x)
i=length(x);
for j=1:1:i
  if(x(j)<0.5)
      a{j,j,:}='low';
  elseif(x(j)==0.5)
      a{j,1,:}='medium';
  else
      a{j,1,:}='high';
  end
end

For example, executing this modified function on your data gives:

classify([0.5 0.1])

ans = 

    'medium'       []
          []    'low'

I don't know if this works correctly throughout the remainder of your application but at least this gives you the proper data structure.

Final comment, I don't understand why you have 3 dimensions in your array, why don't you just use:

function [a]=classify(x)
i=length(x);
for j=1:1:i
  if(x(j)<0.5)
      a{j,:}='low';
  elseif(x(j)==0.5)
      a{j,:}='medium';
  else
      a{j,:}='high';
  end
end

Giving the output (arbitrary input vector):

classify([rand(1,6)])'

ans = 

    'high'    'low'    'high'    'low'    'low'    'low'