1

I am trying to write a simple implementation of a stack in MATLAB, I have used a piece of code earlier in my work similar to:

A = zeros(5,3)
[x, y] = size(A)

This, as expected assigns x to 5, and y to 3, as desired, however I have tried to do a similar thing in my stack implementation and it's throughing an error:

  function [x, y] = pop(obj)
        [x, y] = obj.Data(1, :);
        obj.Data(1, :) = [];
   end

Error: Indexing cannot yield multiple results.

I tried to first extract the 2x1 matrix and then assign it, but that didn't work either:

    function [x, y] = pop(obj)
        top = obj.Data(1, :);
        [x, y] = top;
        obj.Data(1, :) = [];
    end

Error: Too many output arguments

This seems strange to me and an explanation of why this occurs would be very interesting, as well as a work around for this

Thank you.

2
  • What obj is? What is top that comes out? If, as you state, top is a 2x1 matrix, you have to extract the values with x = top(1,1) and y = top (2,1). Commented Sep 5, 2017 at 7:52
  • obj is a 2xn matrix. Commented Sep 5, 2017 at 7:56

1 Answer 1

2

That is because of that size is a function/operation that can return multiple outputs but indexing operations such as Data(1,:) can only return one output as an array, and an array can not be considered as multiple outputs. You can do the following:

top = num2cell(obj.Data(1, :));
[x, y] = top{:}; %or [x, y] = top{1:2};

Here you converted an array to a cell array and by {:} you created a comma separated list that can be assigned to multiple variables.

Or they can be assigned separately

x = obj.Data(1, 1);
y = obj.Data(1, 2);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.