Question

Consider the following MATLAB struct:

a(1).num=1; a(2).num=2; a(3).num=3;

The thing I want to do is to replace some of the elements of num with the old value minus a (scalar) number. For example, I would like to subtract 1 from a(2).num and a(3).num.

I already tried different ways:

a(2:3).num=a(2:3).num-1;


??? Error using ==> minus Too many input arguments.

Next try:

>>a(2:3).num=[a(2:3).num]-1;

??? Insufficient outputs from right hand side to satisfy comma separated list 
expansion on left hand side. Missing [] are the most likely cause.

And last:

>> [a(2:3).num]=[a(2:3).num]-1;

??? Error using ==> minus
Too many output arguments.    

arrayfun couldn´t help either. Probably there is a quite easy answer to this question, but I couldn´t find any.

Was it helpful?

Solution

Easiest is a two-line solution:

C = num2cell([a(2:3).num]-1);
[a(2:3).num] = C{:}

Nicest is to have a function like deal, but with a function applied to each argument:

function varargout = fcnDeal(varargin)

    %// (Copied from MATLAB's deal()

    if nargin==1,
        varargout = varargin(ones(1,nargout));
    else
        if nargout ~= nargin-1
            error('fcnDeal:narginNargoutMismatch',...
                'The number of outputs should match the number of inputs.')
        end
        %//...Except this part
        varargout = cellfun(varargin{1}, varargin(2:end), 'UniformOutput', false);
    end

end

Then what you want to do is just a matter of

[a(2:3).num] = fcnDeal(@(x)x-1, a(2:3).num)

OTHER TIPS

You can manipulate them in the loop

index = [1,2] 
for i = index
a(i).num = a(i).num - 1;
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top