How to index a cell array in a for loop
9 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (3)
Star Strider
el 26 de Feb. de 2022
See if:
base_obs{i} = cell2mat(textscan(fileID, '%f %f %f %f %f %f %f %f'));
produces the desired result.
.
2 comentarios
Stephen23
el 26 de Feb. de 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 comentarios
Voss
el 26 de Feb. de 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 comentarios
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!