How to index a cell array in a for loop

4 ビュー (過去 30 日間)
Terry Poole
Terry Poole 2022 年 2 月 26 日
コメント済み: Star Strider 2022 年 2 月 26 日
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

回答 (3 件)

Star Strider
Star Strider 2022 年 2 月 26 日
See if:
base_obs{i} = cell2mat(textscan(fileID, '%f %f %f %f %f %f %f %f'));
produces the desired result.
.
  2 件のコメント
Terry Poole
Terry Poole 2022 年 2 月 26 日
That did it! Thanks!!
Star Strider
Star Strider 2022 年 2 月 26 日
My pleasure!

サインインしてコメントする。


Stephen23
Stephen23 2022 年 2 月 26 日
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 2022 年 2 月 26 日
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

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by