Read Text File of integers into One 2D matrix in Matlab - arrays

I Matlab I want to read a File of the following format :
1 23 6 547 8 9 .....
56 56 85 2 7 9 ....
I want to read this file and store it in a 2D array that has the same shape as the file. Reading in Matlab seems complicated as it has conversions ratios! and other stuff
Any Help

Maybe you are looking for the function importdata
importdata('test.txt')
ans =
1 2
3 4

You can also use load (assuming a text file named 'a'):
load a

Related

How to display a picture from an array

In order to manipulate images later by swapping pixels ("photobooth transformation"), I started by writing a script to create an array of dimension n x n , from a "photo. png" of n x n pixels. But when I want to check if the table is really the same as the picture, it doesn't work
Here is the script:
from PIL import Image
import numpy as np
#the image is 50x50 pixels in gray mode
im =Image.open(r "D:\0-Python0-Image pixelsphoto.png")
print("size=",im.size," ",'mode=', im.mode," ", "format=",im.format)
im.show()
# Image → numpy array
T= np.array(im)
# array formatting ..there are 50 rows like this one
for i in range(0,50):
print('{:>3d}'.format(T[u][0]),'{:>3d}'.format(T[u][1]),......'{:>3d}'.format(T[u][48]),'{:>3d}'.format(T[u][49]),end=""),print()
Then I copy the table in a text file and save it in the format "photo.pgm" :
P2
49 49
255
18 17 16 12 11 10 11 13 ........ .
19 20 17 14 13 13 13 12 ..........
etc
The script works well, but when I open the file "photo.pgm", the pixels are mixed up and I can't find the initial photo
thank you for your help
thank you pipo1980 for your help
but in the meantime I found an explanation to my problem
In fact in the 50x50 array the indexes are counted between 0 and 49
while in the photo application (GIMP or Photoshop) pixels are counted between 1 and 50
I made the mistake to define the pgm file with the specifications
P2 49 49 255
instead of
P2 50 50 256
So the problem is solved

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;

File format of 2d array octave

I have the following 2d array:
1 2 3
4 5 6
7 8 9
stored in a text file in format: [1 2 3; 4 5 6; 7 8 9;]. However when I try to load this file and save to a variable using:
a = load('data.txt'), it gives me following error:
error: load: unable to determine file format of 'data.txt'
Any suggestion on this would be nice. Thanks.
load only handles ASCII data if it's in the format shown in the first part of your post.
data.txt
1 2 3
4 5 6
7 8 9
And read it using:
data = load('data.txt', '-ascii');
If your data is stored as a formatted string rather than the ASCII matrix shown above, you'll have to read the file in a string and then use str2num to convert it to a 2D array.
fid = fopen('data.txt', 'r');
data = str2num(fread(fid, '*char').');
fclose(fid);
In the future, I would recommend storing matrices as ASCII as shown in the top part of the post

Get average of two consecutive values in a vector depending on logical vector

I am reading data from a file and I am trying to do some manipulation on the vector containing the data basically i want to check if the values come from consecutive lines and if so i want to average each two and put the value in a output vector
part of the data and lines
lines=[153 152 153 154 233 233 234 235 280 279 280 281];
Sail=[ 3 4 3 1.5 3 3 1 2 2.5 5 2.5 2 ];
here is what i am doing
Sail=S(lines);
Y=diff(lines)==1;
for ii=1:length(Y)
if Y(ii)
output(ceil(ii/2))=(Sail(ii)+Sail(ii+1))/2;
end
end
is this correct also is there a way to do that without a for loop
Thanks
My suggestion:
y = find(diff(lines)==1);
output = mean([Sail(y);Sail(y+1)]);
This assumes that when you have, say [233 234 235], you want one value averaging the values from lines [233 234] and one value averaging those from [234 245]. If you wanted to do something more complex when longer sets of consecutive lines exist in your data, then the problem becomes more complex.
Incidentally it's a bad idea to do something like (ceil(ii/2)) - you can't guarantee a unique index for each matching value of ii. If you did want an output the same size as Sail (will have zeros in non-matching areas) then you can do something like this:
output2 = zeros(size(Sail));
output2(y)=output;

What format does matlab need for n-dimensional data input?

I have a 4-dimensional dictionary I made with a Python script for a data mining project I'm working on, and I want to read the data into Matlab to do some statistical tests on the data.
To read a 2-dimensional matrix is trivial. I figured that since my first dimension is only 4-deep, I could just write each slice of it out to a separate file (4 files total) with each file having many 2-dimensional slices, looking something like this:
2 3 6
4 5 8
6 7 3
1 4 3
6 6 7
8 9 0
This however does not work, and matlab reads it as a single continuous 6 x 3 matrix. I even took a look a dlmread but could not figure out how to get it do what I wanted. How do I format this so I can put 3 (or preferably more) dimensions in a single file?
A simple solution is to create a file with two lines only: the first line contains the target array size, the second line contains all your data. Then, all you need to do is reshape the data.
Say your file is
3 2 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
You do the following to read the array into the variable data
fid = fopen('myFile'); %# open the file (don't forget the extension)
arraySize = str2num(fgetl(fid)); %# read the first line, convert to numbers
data = str2num(fgetl(fid)); %# read the second line
data = reshape(data,arraySize); %# reshape the data
fclose(fid); %# close the file
Have a look at data to see how Matlab orders elements in multidimensional arrays.
Matlab stores data column wise. So from your example (assuming its a 3x2x3 matrix), matlab will store it as first, second and third column from the first "slice", followed by the first, second third columns from the second slice and so on like this
2
4
3
5
6
8
6
1
7
4
3
3
6
8
6
9
7
0
So you can write the data out like this from python (I don't know how) and then read it into matlab. Then you can reshape it back into a 3x2x3 matrix and you'll retain your correct ordering.

Resources