简体   繁体   中英

how can i access a vector in Matlab when using anonymous function that requires inputs

I am trying to shuffle a vector that is not yet defined the vector consist of [0 0 0... 0 0 1 2 3... (n-zer)]

  • n : length of vector
  • zer : number of zeros at the beginning

like so:

PartZeroPartNum=@(zer,n) [zeros(1,zer),1:(n-zer)];
shuffled=@(zer,n) PartZeroPartNum(zer,n)(randperm(n));

it does not work as this part

PartZeroPartNum(zer,n)(randperm(n))

gives the error:

cannot call or index into temporary array

In contrast, it is working if I do it this way:

n=100;
PartZeroPartNum=logical([zeros(1,zer),1:(n-zer)]);
shuffled=@() PartZeroPartNum(randperm(n));

Is it possible to shuffle a more versatile vector as I tried to do above? maybe in another way?

The reason is that I need many examples of shuffled vectors so I thought to make this anonymous function first and then take samples easily like so:

ShVec= shuffled(50,100);

There are better ways to do this, but you could add yet another anonymous function

PartZeroPartNum=@(zer,n) [zeros(1,zer),1:(n-excited)];
fIndex = @(x,ii) x(ii);
shuffled=@(zer,n) fIndex(PartZeroPartNum(zer,n), randperm(n));

As mentioned in the comments, you would be better to use a function in its own m-file, this would be the most readable option as suggested by Cris.

The function call equivalence to A(index) is subsref(A, struct('type', '()', 'subs', {index})) see here .

So you can make your anonymous function

PartZeroPartNum=@(zer,n) [zeros(1,zer),1:(n-excited)];
shuffled=@(zer,n) subsref(PartZeroPartNum(zer,n), struct('type', '()', 'subs', {randperm(n)});

But I wouldn't do it as it is not very readable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM