How can I delete a particular element in a set of workspace variables?

조회 수: 5 (최근 30일)
Aaron S
Aaron S 2020년 5월 22일
편집: Fangjun Jiang 2020년 5월 26일
My workspace has a set of variables with a common prefix. Most of the variables are sized 839 X 1 single. But some of these variables are 840 X 1 single. The last element in the 840 X 1 variable has to be deleted. My aim is to use a for loop to go through all the variables in the workspace with the prefix and then delete the last element in variables where there are more than 839 elements.
So far, I used whos to create a structural aray with the details of the variables with the appropriate prefix:
C = whos ('CSUS114_dFF_*')
I then used a for loop to create an array with the names of the variables which need their last element to be deleted:
for r = 1:length(C)
if C(r).size(1)>839
a{r} = C(r).name
end
end
a(cellfun('isempty',a))=[];
This gave me the right result with the names of the variables. However, I am not sure how to proceed to the next step which would be to somehow use this array to delete the last element of the respective variables. Any ideas?
  댓글 수: 3
Deepak Gupta
Deepak Gupta 2020년 5월 26일
I think better would be you reassign your variables with required size. For exp:
x = randn(840, 1); %Variable with size 840*1
x = x(1:839); % Here variable will be truncated to 839*1 if it's more than this size.
Aaron S
Aaron S 2020년 5월 26일
Thank you for these suggestions.
Stephen, I agree - I wanted to avoid using the eval family of functions - which is why I even asked the question.
Deepak, I think your suggestion is a good one - better to truncate earlier as you have pointed out.

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

답변 (1개)

Fangjun Jiang
Fangjun Jiang 2020년 5월 26일
편집: Fangjun Jiang 2020년 5월 26일
For a one-time processing, you can do this
for r = 1:length(C)
if C(r).size(1)>839
str=sprintf('%s(840:end)=[];',C(r).name);
evalin('base',str);
end
end

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by