How to index a cell array in a for loop

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

Antworten (3)

Star Strider
Star Strider am 26 Feb. 2022

1 Stimme

See if:
base_obs{i} = cell2mat(textscan(fileID, '%f %f %f %f %f %f %f %f'));
produces the desired result.
.

2 Kommentare

Terry Poole
Terry Poole am 26 Feb. 2022
That did it! Thanks!!
Star Strider
Star Strider am 26 Feb. 2022
My pleasure!

Melden Sie sich an, um zu kommentieren.

Stephen23
Stephen23 am 26 Feb. 2022

0 Stimmen

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
Voss
Voss am 26 Feb. 2022

0 Stimmen

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

Kategorien

Produkte

Version

R2021b

Gefragt:

am 26 Feb. 2022

Kommentiert:

am 26 Feb. 2022

Community Treasure Hunt

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

Start Hunting!

Translated by