1

I am working in MATLAB and currently have this code:

for i =1:142674:loop_end
data = textread('Results.txt', '%s');
name = data{i};
end

However, I want the name of the data point I select to be stored into an Array where the first name would be the first string in the array and so forth. So at the end I have an array containing all the names gathered from the loop.

3
  • An array can't have strings as keys. Arrays/matrices can only have integers as keys. You have to use cell arrays for that as you have started to do. Commented Jul 11, 2014 at 14:14
  • Maybe Categorical arrays would work for you if your names are a finite set. Commented Jul 11, 2014 at 14:21
  • see this: stackoverflow.com/a/2289119/97160 Commented Jul 11, 2014 at 23:50

2 Answers 2

1

What about this:

counter = 0
for i =1:142674:loop_end
    counter = counter + 1;
    data = textread('Results.txt', '%s');
    myArray{counter} = data{i};
end

myArray will contain the names.

> myarray = 'Name1'  'Name2'  'Name3'  'Name4'

Though, it will actually be a Cell array, not a regular array

Sign up to request clarification or add additional context in comments.

8 Comments

Side-note: In your code, because iteration is stepped iteration (1:142674:loop_end), myArray will contain many empty entries.
@CitizenInsane You are right, thanks for noting. I fixed it by adding a counter.
that works. how can I then call upon the array in a loop to saveas like this: for i:array.length saveas(gcf, 'Name', 'jpeg') ; end So I would have the file name saving as a different name each time and getting those names for the array I created... but I would want the
@user3145111 You can call any string in your array by using myArray{InsertIndexNumberHere}. ie: myArray{2} would give the second Name.
Keep saying, index exceeds matrix dimensions. The array is a 1x6, and the loop goes from 1:6...?
|
1

Why to read the text file multiple times ?

data = textread('Results.txt', '%s');
names = data(1:142674:end);

This way names is a cell array containing 1st, 142675th, etc... strings in the file.

NB: Well maybe I've misunderstood the question.

2 Comments

Your answer is much faster and optimized. I personnaly think yours is much better than mine. +1
Thanks ... The problem is solved, that's the most important ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.