How to reverse a series of variable assignments?

조회 수: 15 (최근 30일)
Michael Van de Graaff
Michael Van de Graaff 2021년 3월 11일
편집: Michael Van de Graaff 2021년 12월 9일
In my code, I frequently have blocks of code of the form
var1 = setting1;
othervar2 = othersetting2;
somevar3 = somesetting3;
where I don't have names of the variables or settings in some way that i can program. Even if i did, I think i would be using eval, and i don't want to do that.
It's common that i later wish to perform analogus assignments in reverse, so i would have a block like
setting1 = var1;
othersetting2 = othervar2;
somesetting3 = somevar3;
This can be very tedious to write out. Does there exist a standard way to performing a line-by-line edit which swaps the left and right side of the variable assignment?
I imagine If i copy the code into a text file, it wouldn't be too hard to write a script that produces a new text file with all the variable assignments swapped, but I wonder if this exists already or if there's a term for this.

채택된 답변

Michael Van de Graaff
Michael Van de Graaff 2021년 3월 11일
I did find a quick solution. On the File Exchange Alessandro Masullo has a function which aligns a block of variable assignments by their equal signs. https://www.mathworks.com/matlabcentral/fileexchange/47918-align-equal-sign
I modified the code to simply place the pre-equal sign part where the post-equal sign part was and vice-versa. my modification is explained in the comments on his alignEquals upload. then running the unmodified alignEquals makes things looks good again.

추가 답변 (1개)

Rik
Rik 2021년 3월 11일
편집: Rik 2021년 3월 11일
I tend to use deal to make it more or less compact:
[var,othervar,somevar]=deal(setting1,othersetting,somesetting);
Now if I want to reverse this I only need to swap the parts between the braces and parentheses, which is easy and fast.
However, you could do some magic with eval (and inputname to make it somewhat robust). The result will not be very clean. You might also consider something like the function below.
function varargout=flipflop_assign(order,varargin)
varargout=varargin(order);
end
  댓글 수: 6
Michael Van de Graaff
Michael Van de Graaff 2021년 4월 1일
편집: Michael Van de Graaff 2021년 12월 9일
I don't think the %% works in App Designer
edit: this is no longer ture if it was true when I made that comment
Rik
Rik 2021년 4월 2일
That might be the case. I never use AppDesigner, but I always create GUIs in the normal editor (and I would do so for a class-based GUI as well).

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Entering Commands에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by