How to index a cell array in a for loop
9 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
So my code works, but it will only show the first file. I have 9 files that will return an 895 x 8 array each, i'm using a for loop to index each file and generate each array, clearly i'm not indexing something correctly, any help would be appreciated.
clear all; close all; clc;
sat = {'data_base\icp_sat2.txt', 'data_base\icp_sat4.txt', ...
'data_base\icp_sat5.txt', 'data_base\icp_sat9.txt', ...
'data_base\icp_sat10.txt', 'data_base\icp_sat12.txt', ...
'data_base\icp_sat17.txt', 'data_base\icp_sat23.txt', ...
'data_base\icp_sat25.txt'};
sats = cell2mat(sat);
base_obs = [];
for i = 1:length(sat)
fileID = fopen(sat{i}, 'r');
base_obs = cell2mat(textscan(fileID, '%f %f %f %f %f %f %f %f'));
fclose(fileID);
end
0 commentaires
Réponses (3)
Star Strider
le 26 Fév 2022
See if:
base_obs{i} = cell2mat(textscan(fileID, '%f %f %f %f %f %f %f %f'));
produces the desired result.
.
2 commentaires
Stephen23
le 26 Fév 2022
P = 'data_base';
V = [2,4,5,9,10,12,17,23,25];
N = numel(V);
C = cell(1,N);
for k = 1:N
F = sprintf('icp_sat%d.txt'V(k));
C{k} = readmatrix(fullfile(P,F));
end
0 commentaires
Voss
le 26 Fév 2022
Your code is overwriting base_obs each time through the loop.
You can make base_obs a cell array, with each cell containing a matrix of data from a file:
clear all; close all; clc;
sat = {'data_base\icp_sat2.txt', 'data_base\icp_sat4.txt', ...
'data_base\icp_sat5.txt', 'data_base\icp_sat9.txt', ...
'data_base\icp_sat10.txt', 'data_base\icp_sat12.txt', ...
'data_base\icp_sat17.txt', 'data_base\icp_sat23.txt', ...
'data_base\icp_sat25.txt'};
% sats = cell2mat(sat);
base_obs = cell(1,numel(sat));
for i = 1:length(sat)
fileID = fopen(sat{i}, 'r');
base_obs{i} = cell2mat(textscan(fileID, '%f %f %f %f %f %f %f %f'));
fclose(fileID);
end
Or, since all your matrices are the same size, you can make base_obs a 3D array with the third dimension corresponding to the different files:
clear all; close all; clc;
sat = {'data_base\icp_sat2.txt', 'data_base\icp_sat4.txt', ...
'data_base\icp_sat5.txt', 'data_base\icp_sat9.txt', ...
'data_base\icp_sat10.txt', 'data_base\icp_sat12.txt', ...
'data_base\icp_sat17.txt', 'data_base\icp_sat23.txt', ...
'data_base\icp_sat25.txt'};
% sats = cell2mat(sat);
base_obs = [];
for i = 1:length(sat)
fileID = fopen(sat{i}, 'r');
base_obs(:,:,i) = cell2mat(textscan(fileID, '%f %f %f %f %f %f %f %f'));
fclose(fileID);
end
0 commentaires
Voir également
Catégories
En savoir plus sur Matrix Indexing 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!