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.

Prefoninsane
  • 103
  • 1
  • 11
  • 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. – kkuilla Jul 11 '14 at 14:14
  • Maybe [Categorical arrays](http://www.mathworks.co.uk/help/matlab/matlab_prog/create-categorical-arrays.html) would work for you if your names are a finite set. – kkuilla Jul 11 '14 at 14:21
  • see this: http://stackoverflow.com/a/2289119/97160 – Amro Jul 11 '14 at 23:50

2 Answers2

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

Sifu
  • 1,082
  • 8
  • 26
  • Side-note: In your code, because iteration is stepped iteration (`1:142674:loop_end`), `myArray` will contain many empty entries. – CitizenInsane Jul 11 '14 at 15:20
  • @CitizenInsane You are right, thanks for noting. I fixed it by adding a counter. – Sifu Jul 11 '14 at 15:23
  • 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 – Prefoninsane Jul 11 '14 at 16:47
  • @user3145111 You can call any string in your array by using `myArray{InsertIndexNumberHere}`. ie: myArray{2} would give the second Name. – Sifu Jul 11 '14 at 16:50
  • Keep saying, index exceeds matrix dimensions. The array is a 1x6, and the loop goes from 1:6...? – Prefoninsane Jul 11 '14 at 16:54
  • Are you sure it only loops from 1 to 6? The only way for it to throw that exception is if the index exceeds the cell dimensions. Try entering `> size(myArray)` and see what it gives. – Sifu Jul 11 '14 at 16:58
  • gives: ans = 1 6 – Prefoninsane Jul 11 '14 at 17:00
  • Try debugging (going step by step in your code) to see what it does. Because if you wrote `for i:length(myArray)`, I don't see why it shouldn't work. – Sifu Jul 11 '14 at 17:03
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.

CitizenInsane
  • 4,755
  • 1
  • 25
  • 56