Leave one out of an array in a for loop

12 次查看(过去 30 天)
Joana
Joana 2021-2-20
回答: Deepak 2024-8-21,11:30
Dear all
I have a program where i need to save one variable separately and concatenate i-1 elements in another variable (Then i need to perform some data analysis these two new variables). here is my code where i am concatenating all the elements.
Can anyone please help how i can edit it according to my problem.?
for i=1:30
resultFileName = sprintf('Sub%i.mat',i); % generate result filename
load(resultFileName)
Es{i} = feat'; % Make a cell array
feat_Concatenate = vertcat(Es{:}); % concatenate the array
end

回答(1 个)

Deepak
Deepak 2024-8-21,11:30
Hi @Joana, from my understanding, you have generated a “feat_Concatenate” array in which you have concatenated all the features. You want to concatenate all the rest elements (1:i-1), other than the ith element together to perform analysis on them.
To perform this task, we can use array indexing in MATLAB to save current feature and other features in different variables.
currentFeature = Es{i};
otherFeatures = Es([1:i-1, i+1:end]); % Get all elements except the i-th one
If you want to concatenate the features from 1 to i-1 and not the later ones, we can use the below notation:
otherFeatures = Es([1:i-1]);
Below is the complete MATLAB code with changes:
Es = cell(1, 30);
feat_Concatenate = cell(1, 30);
for i = 1:30
resultFileName = sprintf('Sub%i.mat', i);
load(resultFileName)
Es{i} = feat';
% Save the current feature separately
currentFeature = Es{i};
otherFeatures = Es([1:i-1, i+1:end]); % Get all elements except the i-th one
feat_Concatenate{i} = vertcat(otherFeatures{:}); % Concatenate the remaining features
% Perform your data analysis with currentFeature and feat_Concatenate{i}
end
Attaching the documentation of Array Indexing in MATLAB for reference:
I hope this helps.

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by