Putting similar named variables into one vector or structure
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Asher Metzger
le 21 Juil 2015
Modifié(e) : Stephen23
le 19 Juin 2019
Hi,
I'm trying with no succes to put variables that have the same construct into one vector: C_100, C_200 and so on into vedctor C. I also want to put Arrays of (44,2) with similar names into a structure: Q_100, Q_200 and so on into a structure Q. Is there a simple way to loop through it?
Thanks in advance, Asher
6 commentaires
Stephen23
le 21 Juil 2015
Modifié(e) : Stephen23
le 21 Juil 2015
It sounds like your .mat files have different data in them, and so the output of load has different fields in its structure. Structures with different fields cannot be concatenated together, thus the error. One possible solution is to use load's optional argument to only read the same variable/s from each .mat file. Here is a complete working example of how to do this:
A = [1,2,3];
save('temp1','A');
A = [4,5,6];
save('temp2','A');
A = [7,8,9];
B = NaN;
save('temp3','A','B'); % <- different number of fields!
D = dir('temp*.mat');
N = {D.name};
for k = numel(N):-1:1
S(k) = load(N{k},'A'); % Specify 'A' only
end
If you remove the 'A' from the load command then it give the same error as you are getting, but with this optional argument it will only load the A field, so no error. Here are some ways of accessing the data in the structure S:
>> S(2).A % indexing single element
ans =
4 5 6
>> horzcat(S(2:3).A) % subset indexing
ans =
4 5 6 7 8 9
>> vertcat(S.A) % all data
ans =
1 2 3
4 5 6
7 8 9
>> {S.A} % all into a cell array
ans =
[1x3 double] [1x3 double] [1x3 double]
And believe you me, this is much more reliable and faster than trying to use dynamically named variables!
Plus de réponses (1)
Azzi Abdelmalek
le 21 Juil 2015
Modifié(e) : Azzi Abdelmalek
le 21 Juil 2015
v={'C_100','aze','C_200'}
C=regexp (v,'C_\d+','match')
idx=~cellfun (@isempty,C)
outc=C (idx)
0 commentaires
Voir également
Catégories
En savoir plus sur Structures dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!