Jakub Jon
Jakub Jon

Reputation: 53

Matlab: Multiple assignment through logical indexing

I am wondering if there is some way, how to multiple assign values to different variables according logical vector.

For example:

I have variables a, b, c and logical vector l=[1 0 1] and vector with values v but just for a and c. Vector v is changing its dimension, but everytime, it has the same size as the number of true in l.

I would like to assign just new values for a and c but b must stay unchanged.

Any ideas? Maybe there is very trivial way but I didn't figure it out.

Thanks a lot.

Upvotes: 3

Views: 269

Answers (1)

Daniel
Daniel

Reputation: 36720

I think your problem is, that you stored structured data in an unstructured way. You assume a b c to have a natural order, which is pretty obvious but not represented in your code.

Replacing a b c with a vector x makes it a really easy task.

x(l)=v(l);

Assuming you want to keep your variable names, the simplest possibility I know would be to write a function:

function varargout=update(l,v,varargin)
varargout=varargin;
l=logical(l);
varargout{l}=v(l);
end

Usage would be:

[a,b,c]=update(l,v,a,b,c)

Upvotes: 1

Related Questions