How to load the multiple data to x by x array in MATLAB? - arrays

I have a bunch of .txt text files. this file is included like this
e.g.
text1.txt-
1
44
22
100
..
..
text2.txt-
7
14
82
50
..
..
....
text260.txt-
31
4
62
700
..
..
like this, text#.txt have almost 260 files.
I want to load into MATLAB with array like this.
a =
1 7 ... 31
44 14 ... 4
22 82 ... 62
100 50 ... 700
.. .. ... ..
.. .. ... ..
As I know, the load() function is in MATLAB. But I don't know how to load into array format.
How to load the multiple data to x by x array in MATLAB ?

You would have to slowly build up the array. My first thought would be to do this:
arr = [];
for i = 1:260
arr = [arr; load(['text' num2str(i) '.txt'])'];
end
You start off with an empty array, and then iterate through the files, appending each file to the array. NB, if the final array is quite large you might want to consider a different approach involving pre-allocating the array:
arr = zeros(length(load('text1.txt')), 260);
for i = 1:260
arr(:,i) = load(['text' num2str(i) '.txt'])';
end

Related

Importing the result of a MATLAB numeric array into a new MATLAB script

Consider that I have a code that returns a double array. When run, the result returned at the command window a result looks like this:
mpc.gen=
1 100 344 34 5
2 433 223 45 2
3 333 432 12 3
4 213 233 12 3
What I want to do is create a MATLAB script which would contain this array. In other words in this new MATLAB script I would have the following array, constructed like this:
mpc.gen= [ 1 100 344 34 5 ;
2 433 223 45 2 ;
3 333 432 12 3 ;
4 213 233 12 3 ;
] ;
Just calling the function would save the variable in the new script, however that is not what I need since I need to use this script for a simulation at a special power tool called MATPOWER. The array needs to be in the form shown at the new script.
The actual array is much bigger in size however I use this here for simplicity. Is there any way I can do this automatically, and not just pass the data from the command window to the new script one by one manually? Any help would be greatly appreciated. Thank you in advance for your time!
What you want to use is mat2str. It converts a matrix to a string representation that, when evaluated, results in the identical matrix.
For example:
>> result = [1 100 344 34 5;
2 433 223 45 2;
3 333 432 12 3;
4 213 233 12 3];
>> mat2str(result)
ans =
[1 100 344 34 5;2 433 223 45 2;3 333 432 12 3;4 213 233 12 3]
You could write this to a file like so:
f = fopen('test_script.m', 'w');
fprintf(f,'mpc.gen = %s\n', mat2str(result));
fclose(f);
The formatting is not identical to your example, but if the tool does proper MATLAB parsing, it shouldn't be a problem.
Is it intentional that mpc is a struct? (you are using dot in the name.) In the following, I use underscore instead, but it can certainly be adopted, if it is intentional.
This is what functions are for. So instead of making a script, you should create a new function. If I were to do what you want to do, I would have 2 functions and 1 script. Whereas the script looks like this
mpc_bus = function1;
function2(mpc_bus);
where function1 is the code that returns mpc.bus and function2 is the one where you want to work with mpc.gen, and the top would be something like this
function [] = function2(mpc_gen)
Alternatively: If you of some reason does not like functions, you can make the first code save the variable using save(*filename*.mat) and then you can load the file again in the script using dat=load(*filename*.mat); and mpc_gen = dat.mpc_bus;

Multi-Dimensional Arrays Julia

I am new to using Julia and have little experience with the language. I am trying to understand how multi-dimensional arrays work in it and how to access the array at the different dimensions. The documentation confuses me, so maybe someone here can explain it better.
I created an array (m = Array{Int64}(6,3)) and am trying to access the different parts of that array. Clearly I am understanding it wrong so any help in general about Arrays/Multi-Dimensional Arrays would help.
Thanks
Edit I am trying to read a file in that has the contents
58 129 10
58 129 7
25 56 10
24 125 25
24 125 15
13 41 10
0
The purpose of the project is to take these fractions (58/129) and round the fractions using farey sequence. The last number in the row is what both numbers need to be below. Currently, I am not looking for help on how to do the problem, just how to create a multidimensional array with all the numbers except the last row (0). My trouble is how to put the numbers into the array after I have created it.
So I want m[0][0] = 58, so on. I'm not sure how syntax works for this and the manual is confusing. Hopefully this is enough information.
Julia's arrays are not lists-of-lists or arrays of pointers. They are a single container, with elements arranged in a rectangular shape. As such, you do not access successive dimensions with repeated indexing calls like m[j][i] — instead you use one indexing call with multiple indices: m[i, j].
If you trim off that last 0 in your file, you can just use the built-in readdlm to load that file into a matrix. I've copied those first six rows into my clipboard to make it a bit easier to follow here:
julia> str = clipboard()
"58 129 10\n58 129 7\n25 56 10\n24 125 25\n24 125 15\n13 41 10"
julia> readdlm(IOBuffer(str), Int) # or readdlm("path/to/trimmed/file", Int)
6×3 Array{Int64,2}:
58 129 10
58 129 7
25 56 10
24 125 25
24 125 15
13 41 10
That's not very helpful in teaching you how Julia's arrays work, though. Constructing an array like m = Array{Int64}(6,3) creates an uninitialized matrix with 18 elements arranged in 6 rows and 3 columns. It's a bit easier to see how things work if we fill it with a sensible pattern:
julia> m .= [10,20,30,40,50,60] .+ [1 2 3]
6×3 Array{Int64,2}:
11 12 13
21 22 23
31 32 33
41 42 43
51 52 53
61 62 63
This has set up the values of the array to have the row number in their tens place and the column number in the ones place. Accessing m[r,c] returns the value in m at row r and column c.
julia> m[2,3] # second row, third column
23
Now, r and c don't have to be integers — they can also be vectors of integers to select multiple rows or columns:
julia> m[[2,3,4],[1,2]] # Selects rows 2, 3, and 4 across columns 1 and 2
3×2 Array{Int64,2}:
21 22
31 32
41 42
Of course ranges like 2:4 are just vectors themselves, so you can more easily and efficiently write that example as m[2:4, 1:2]. A : by itself is a shorthand for a vector of all the indices within the dimension it indexes into:
julia> m[1, :] # the first row of all columns
3-element Array{Int64,1}:
11
12
13
julia> m[:, 1] # all rows of the first column
6-element Array{Int64,1}:
11
21
31
41
51
61
Finally, note that Julia's Array is column-major and arranged contiguously in memory. This means that if you just use one index, like m[2], you're just going to walk down that first column. As a special extension, we support what's commonly referred to as "linear indexing", where we allow that single index to span into the higher dimensions. So m[7] accesses the 7th contiguous element, wrapping around into the first row of the second column:
julia> m[5],m[6],m[7],m[8]
(51, 61, 12, 22)

Storing blocks of vector data into an array in Matlab

I have an array in Matlab
A = [1 2 3 4 5 6 7 8 9;
67 67 67 86 86 86 86 67 67]';
where every point in the first row of A corresponds to a "code" either 67 or 86. I am trying to extract these blocks of "67s" and "86s" such that every time a block starts the corresponding elements are put into the 3rd dimension of a different array called X, where the .
So for e.g. in A I have 3 different blocks, so I would like to end up with an array X of size 1x9x3. And for e.g. the first 67 block I would like to have X
X(1,:,1) = [1 2 3];
I understand that I would "fill up" this vector X using a for loop
for i=1:size(A,2)
for j=1:size(A,2) %actually j should be up till the number of blocks present
X(1,i,j) = A(1,i)
end
end
But this isn't correct or complete of course because firstly I'm unsure how to separate out the "blocks" and how to correctly "fill in" the j's in X(1,i,j). Secondly how can I get the code to recognise how many blocks there are?
Can anyone help?
Thanks
One possible approach, based on this answer:
>> B = accumarray([0; cumsum(diff(A(:,2)) ~= 0)] + 1, A(:,1), [], #(x) {x}, [])
Now you have this:
>> B{1}
ans =
1
2
3
>> B{2}
ans =
4
5
6
7
>> B{3}
ans =
8
9

How to store the Centroid values of blobs in one Array?

My picture has a certain number of various shapes of blobs. I want to store those centroid values in one array for the future use. So I tried the following code, but it did not work. So can anyone help me?
Sample:
for i = 1:length(STATS)
centroid = STATS(i).Centroid;
array = zeros(length(STATS));
array(i) = centroid;
end
I want to store the centroid data in one array like below
array=
145 145
14 235
145 544
14 69
74 55
Try the following:
for i = 1:length(STATS)
array{i} = STATS(i).Centroid;
end
You can print the entire array using the following:
array{:}
You can read more about cell arrays here. Also, in your older code, you were trying to assign an array (Centroid) to an element of an array(array(i)).
How about:
array=cell2mat({STATS.Centroid});
Assuming
STATS(1).Centroid = [145 145];
STATS(2).Centroid = [14 235]; % Etc...
Try:
array = reshape([STATS.Centroid],2,size(STATS,2))'
array =
145 145
14 235
145 544
14 69
74 55
How this works:
[STATS.Centroid] is a short version of [STATS(1).Centroid, STATS(2).Centroid, .. STATS(n).Centroid]. This will give you the values as a vector. reshape is then used to make it into your desired size.

Importing text files with comments in MATLAB

Is there any character or character combination that MATLAB interprets as comments, when importing data from text files? Being that when it detects it at the beginning of a line, will know all the line is to ignore?
I have a set of points in a file that look like this:
And as you can see he doesn't seem to understand them very well. Is there anything other than // I could use that MATLAB knows it's to ignore?
Thanks!
Actually, your data is not consistent, as you must have the same number of column for each line.
1)
Apart from that, using '%' as comments will be correctly recognized by importdata:
file.dat
%12 31
12 32
32 22
%abc
13 33
31 33
%ldddd
77 7
66 6
%33 33
12 31
31 23
matlab
data = importdata('file.dat')
2)
Otherwise use textscan to specify arbitrary comment symbols:
file2.dat
//12 31
12 32
32 22
//abc
13 33
31 33
//ldddd
77 7
66 6
//33 33
12 31
31 23
matlab
fid = fopen('file2.dat');
data = textscan(fid, '%f %f', 'CommentStyle','//', 'CollectOutput',true);
data = cell2mat(data);
fclose(fid);
If you use the function textscan, you can set the CommentStyle parameter to // or %. Try something like this:
fid = fopen('myfile.txt');
iRow = 1;
while (~feof(fid))
myData(iRow,:) = textscan(fid,'%f %f\n','CommentStyle','//');
iRow = iRow + 1;
end
fclose(fid);
That will work if there are two numbers per line. I notice in your examples the number of numbers per line varies. There are some lines with only one number. Is this representative of your data? You'll have to handle this differently if there isn't a uniform number of columns in each row.
Have you tried %, the default comment character in MATLAB?
As Amro pointed out, if you use importdata this will work.

Resources