How to best scan a table for same element values and create arrays to store the extracted data successively?

6 views (last 30 days)
I have a dataset like such: A text file with three columns Var1, Var2 and Var3.
In Var1 there are many elements of the same name to be exact in the following format: 0000000004 and when it reaches the 100 it becomes 0000000100.
UPDATE: I forgot to mention I used readtable to read in the values and set them up in a table in the below format.
My goal is to loop through the elements of Var1 and pick out the Var2 and Var3 values of the same Var1 and save them to a seperate array holding Var2 and Var3
Example: Var1 Var2 Var3
0000000004 5 6
0000000004 7 8
0000000004 9 10
0000000005 11 12
0000000005 13 14
.. .. ..
This will become Array4 = 4 6
7 8
9 10
Array5 = 11 12
13 14
and so on..
being new to matlab(coming from C++ background) the task has been harder than I anticipated. The place where I am struggling is to write a loop that changes the values I am searching for automatically, like how do I replace the numbering from 0000000004.png to 0000000010.png (replacing the zero with a 1 without going through a lot of trouble) and I am not sure how to search for a string value (since it is not only numbers). Could you please give me a few hints of how to start ?
- I am going to iterate through the values of variable one via a for loop
- when there is a new value of Var1 I will create an array for storing its Var2 and Var3 values
- the whole procedure is put in a for loop to make it easier for the process to be repeated when a new 000000000x.png value appears in the Var1 column

Accepted Answer

Guillaume
Guillaume on 26 Feb 2015
1) Do not create numbered variable names (names that you would have to generate dynamically), use the adequate container for your data, which is a cell array in your case.
2) You mention a table in your question's title but a file in the question's body. So what have you got?
3) I would read the file all at once in a cell array and then use unique and a loop to split the cell array into what you want:
fid = fopen('somefile.txt', 'rt');
allfiledata = textscan(fid, '%s %f %f'); %create a cell array with 3 columns
[var1, ~, locations] = unique(allfiledata{1});
subarrays = cell(1, numel(var1));
fullmatrix = cell2mat(allfiledata(2:end));
for varindex = 1:numel(var1)
subarrays{varindex} = fullmatrix(locations == varindex, :);
end
celldisp(subarrays)
  5 Comments
KBK007
KBK007 on 27 Feb 2015
@Guillaume Thank you for your answer, I get it now. The problem is going from C++ to Matlab is not an easy process, I have to get used to how Matlab works with its data. That is why I am reading a guide and acquiring the logic behind data handling in Matlab.

Sign in to comment.

More Answers (0)

Categories

Find more on Cell Arrays in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!