필터 지우기
필터 지우기

How to index a cell array in a for loop

조회 수: 9 (최근 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 CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by