Bala
Bala

Reputation: 67

Remove first 2 letters from workspace variables

Let's say I have a .mat file and I know that each of the variables in it has XY in front of it (e.g. XYJanuary, XYFebruary, XYMarch and so on...) and I just want to remove the XY.

I have looked at this and tried to copy it but this adds the XY to my variable (XYXYJanuary, XYXYFebruay,...) but I want it to be just (January, Februay,...).

x= load('file.mat');                             % Load into structure x
names=fieldnames(x);                             % names of the variables
  for iname=1:length(names)                      % start the loop 
    x.(['XY', names{iname}]) = x.(names{iname}); % PROBLEM
    x = rmfield(x, names{iname});
  end
save ('newfile.mat', '-struct', 'x');            %save

Upvotes: 0

Views: 50

Answers (1)

Adriaan
Adriaan

Reputation: 18177

x= load('file.mat');                              % Load into structure x
names=fieldnames(x);                              % names of the variables
  for iname=1:length(names)                       % start the loop 
    x.([names{iname}(3:end)]) = x.(names{iname}); % No more PROBLEM
    x = rmfield(x, names{iname});
  end
save ('newfile.mat', '-struct', 'x');             % save

You added the 'XY' to the LHS of your line, that makes it add it to the final solution. What I did is to chop off the first two entries, but keep the rest, hence the (3:end). This now works on a test case I created.

Upvotes: 1

Related Questions