How to extract values from an array and write at a specific cell of a matrix?

8 views (last 30 days)
INTRODUCTION: Hi, I have multiple arrays i.txt made of two columns and n-rows in a folder. The examples below display the first two arrays:
% 1.txt
fid =fopen('C:\Users\EMERSON\Desktop\ARRAYS\1.txt');
A1=textscan(fid,'%f %f');
% 3 130
% 4 340
% 5 159
% 6 030
% 7 100
% 2.txt
fid =fopen('C:\Users\EMERSON\Desktop\ARRAYS\2.txt');
A2=textscan(fid,'%f %f');
% 10 125
% 11 300
% 12 110
GOAL: I want to construct a matrix M with elements of the second column of i.txt as below:
1 2 3 4 5 6 7 8 9 10 11 12 13
NaN NaN 130 340 159 030 100 NaN NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN NaN NaN NaN NaN 125 300 110 NaN
A value is assigned for each column of M (First row of M above, but it will not appear later, I display here only for clarification).
Then I import the array 1.txt. If the first column of the array 1.txt contains a value assigned in M, then I extract the corresponding value from the second column of 1.txt and write in the cell of the matrix designed for it (first row and j-column).
And I write NaN (not available) in the cells of M for which the value is not found in i.txt.
Then I import the array 2.txt and do the same in the second row of the matrix, and so on for i.txt arrays. The resulting matrix will contain i-rows and j-columns, where j is the range of values pre-assigned.
I wonder if someone could help me how to write the commands that does this extraction and write in the proper place of the matrix.
Thank you in advance for your help

Accepted Answer

Chad Greene
Chad Greene on 6 Nov 2012
Edited: Chad Greene on 6 Nov 2012
Try this, and replace numberoffiles with how many .txt files you have. Also if you have more than 13 columns in you M matrix, change numberofcolumns accordingly:
M = NaN(numberoffiles,numberofcolumns); % preallocates matrix for speed
for filenumber = 1:numberoffiles
fid =fopen(['C:\Users\EMERSON\Desktop\ARRAYS\',num2str(numberoffiles),'.txt']);
A=textscan(fid,'%f %f');
A = cell2mat(A);
M(filenumber,A(:,1)) = A(:,2);
Emerson De Souza
Emerson De Souza on 8 Nov 2012
Hi Chad, thanks again for your help.
You gave a great suggestion and my problem is partially solved.
I will formulate the specific problems in a new question and address them with more clear example.
Wish you a nice evening

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by