当前位置:网站首页>[matlab] access of variables and files
[matlab] access of variables and files
2022-07-06 02:35:00 【Magical ALU】
Through the previous study, we have clearly understood some classifications of variables , Here I post one again MATLAB The types of variables in :
Cast variable

incomprehension ?
Please look at the following operation :

A By default double type ,B Yes A Cast


character
c='a';Characters have their own storage methods in computer storage , Because computer storage is based on binary storage , How to store characters ? Store some numbers instead of them , And out of that came ASCII CODE.
string
string concatenation
You can define string variables in the following way
s1='Example';
s2='String';First, we can connect strings
Please try these two ways :
s3=[s1 s2];
s4=[s1;s2];
We found that s3 It can be executed , however s4 Can't execute ,why?Example Yes 7 Characters ;String Yes 6 Characters ; Different lengths cannot form a matrix

string indexing
The index of characters in a string is very similar to an array , Note that you may have learned C Language students are very unfriendly , The index is from 1 Start not from 0 Start .

string comparing
Comparison of characters and strings

When comparing individual characters, we will find , Compare this character with each character in the string , If equal, the position is 1, If you don't wait, it's 0, Then output a binary logic vector .
How to compare the whole string ?
Some students with programming experience may go directly == But in MATLAB It can't be used inside ! Only strings with the same dimension can be used
'example'=='example'% Sure
'example'=='amp'% Can not be I wrote a custom here function:
function string_compare(s1,s2)
if length(s1)~=length(s2)
disp('0');
else
i=1;
while i<=length(s1)
if s1(i)~=s2(i)
break;
end
i=i+1;
end
if i==length(s1)+1
disp('1');
else
disp('0');
end
endeffect :

however ! however ! however ! Please note that , My knowledge is simple compare, How to output logical Input to the ans? It has to be MATLAB Library function strcmp And strcmpi; The difference between the former and the latter is that the former is case sensitive , The latter is case insensitive ; as follows :

string replacing
We can try the following experiment :

You can replace some characters in the string in this way .
Replace the character at a certain position by index :

Exercise

Write a function that inverts a string
Refer to the following :
function s2=invert(s1)
for i=length(s1):-1:1
s2(abs(i-length(s1))+1)=s1(i);
endRunning results :

But this way of writing has some C The taste of language , Not concise !
function s2=invert(s1)
s2=s1(length(s1):-1:1);
Only in this way can there be matlab The smell of
structure( Structure )
stay matlab A structure is set in the following way to store different types of data in a variable .
s=struct('field1',value1,'field',value2,...)
Of course, it can also be assigned in this way

Then let's see student This variable will find :

Structure Functions
| cell2struct | Convert cell array to structure array |
|---|---|
| fieldnames | Get the property bar of the structure or the public property bar of the class |
| getfield | Get the property bar in the structure |
| isfield | Determine the input string ( Array of strings ) Is it a property bar in a structure ; The result returned is a logical matrix |
| isstruct | Judge whether the input is a structure |
| orderfields | Sort the property bar ( according to ASCII) |
| rmfield | Delete the attribute bar in the structure |
| setfield | Assign values to the property bar |
| struct | Create a structure |
| struct2cell | Convert the structure into an array of cells |
| structfun | Apply functions to elements in the structure |
| arrayfun | Apply functions to elements in the structure ( The difference from the above is structfun The parameter of must be a scalar structure ) |
Structure is divided into scalar structure and structure array , The structure array can be accessed through the index of the structure array , Scalar structures can be accessed by their names .
The attribute in a structure can also be a structure , Unlimited dolls
cell
Declare use cell array Use {};
There are two ways to define a new structure array :

We see the A You can see :


cell The index of
Like the one I created above cell equally , How do I access the elements ?
There are two ways, such as accessing the first matrix
A(1,1)
A{1,1}
There is an obvious gap between the two .
So how to get the elements in this matrix ?

Actually cell Each element of the array is equivalent to a pointer , This pointer points to the one you originally created cell The data specified when .A{1,1} Is the operation of a pointer ,A{1,1} Point to the matrix above .
Cell Array Functions

Except for that, of course function There are other functions , You can directly Baidu when you need it
Next we will focus on the difference between the two functions :
mat2cell And num2cell
num2cell It is to make each element of the matrix into a cell The elements of


mat2cell Is to set which rows or columns are new cell Elements . Be careful mat2cell The sum of row parameters and column parameters should be the number of rows and columns of the matrix


The three dimensional matrix

cat
use cat Function to add dimensions


reshape()
Yes cell Reshape . primary cell The number of rows x Number of columns = new cell The number of rows x Number of columns

there A It turned out to be a 2X2 Of cell, after reshape The function then becomes a 1x4 The new cell
And cell dependent function

File<--->Data
Ordinary documents
How to store my data in a file ?
The data I processed is stored in Workspace Inside , But we got here and found that every time I restart matlab It'll empty workspace The data in it , I can't keep it on matlab Well ! Besides, users use matlab It's not a project . therefore , about workspace The data stored in the form of files needs to be learned .
We usually use these three methods :
| The contents of the document | extension | describe | File open function | File saving function |
|---|---|---|---|---|
| MATLAB Type file | .mat | preservation MATLAB Of workspace The data in | load | save |
| Text | Numbers with spaces | load | save | |
| Hash table | .xls/.xlsx | xlsread | xlswrite |
Mode one :

We are in accordance with the MATLAB Go to the file directory above to find our data :

We use Notepad to open it and find :

The first line is the file information , The second line is the content of the file. It is found that what we present is a pile of garbled code. Why ?
When we write code with Notepad, there will also be some compilation errors when typing Chinese , That's because the encoding method of text storage is wrong , Use ascii Coding method of . So can we use it when we store it ascii What is the way? ?
The answer is yes !
Followed by -ascii that will do !


The format of numbers has changed into the format of science and Technology Law
How to open a file ?
Use load function :


How to store a specific variable ?


Excel Example reading :
give an example :
We have one of the following excel surface :

How to integrate excel Put your data into workspace?

We found that using xlsread Function can read in numbers but not strings
Of course, it can be in read The second parameter of is set to the read range :

Process data and write excel file :

Finding such a problem as the scarlet letter , That's because of my office Is still in the process of opening this excel The state of , close office that will do

Retype :

What does the parameter here mean ?
xlswrite(filename, Variable ,sheet, Table location );
However, the average value I calculated also needs a header ; So it can also be like this :


If the set parameter is not {'Mean'} It is 'Mean', Will write excel The following situations will appear when you use the form :

write in excel It should also be like cell The same as variables of type .
But one excel Only numbers are valuable ? Are those words worthless ?
Obviously, it's wrong to think so , How to read these words ?

How to write words and numbers into excel?
Write in two steps :

Simple writing and writing of files :
The following functions are involved :


for example :
X=0:pi/10:pi;
Y=sin(X);
fid=fopen('sin.txt','w');
for i=1:11
fprintf(fid,'%5.3f %8.4f\n',X(i),Y(i));
end
fclose(fid);And then we type sin.txt This file

At the same time, we can also find it under the current folder sin.txt Then look at this file :

there %5.3f and %8.4f Is the output format 5.3 It means that the number is composed of 5 Of which 3 Numbers are after the decimal point , The latter is similar to
How to read ?


边栏推荐
- Compact lidar global and Chinese markets 2022-2028: technology, participants, trends, market size and share Research Report
- How to check the lock information in gbase 8C database?
- Yyds dry inventory comparison of several database storage engines
- [Wu Enda machine learning] week5 programming assignment EX4 - neural network learning
- Redis delete policy
- 纯Qt版中国象棋:实现双人对战、人机对战及网络对战
- What should we pay attention to when using the built-in tool to check the health status in gbase 8C database?
- Formatting occurs twice when vs code is saved
- Six stone management: why should leaders ignore product quality
- 我把驱动换成了5.1.35,但是还是一样的错误,我现在是能连成功,但是我每做一次sql操作都会报这个
猜你喜欢

一位博士在华为的22年

纯Qt版中国象棋:实现双人对战、人机对战及网络对战
![[community personas] exclusive interview with Ma Longwei: the wheel is not easy to use, so make it yourself!](/img/aa/af98b588efd61d71b1b02609817c49.png)
[community personas] exclusive interview with Ma Longwei: the wheel is not easy to use, so make it yourself!
![[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 24](/img/2e/b1f348ee6abaef24b439944acf36d8.jpg)
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 24

2022 China eye Expo, Shandong vision prevention and control exhibition, myopia, China myopia correction Exhibition

主数据管理(MDM)的成熟度

【MySQL 15】Could not increase number of max_ open_ files to more than 10000 (request: 65535)

Li Kou today's question -729 My schedule I

Shell脚本更新存储过程到数据库

Yyds dry inventory comparison of several database storage engines
随机推荐
"Hands on learning in depth" Chapter 2 - preparatory knowledge_ 2.3 linear algebra_ Learning thinking and exercise answers
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 20
Spherical lens and cylindrical lens
Multiple solutions to one problem, asp Net core application startup initialization n schemes [Part 1]
Paper notes: graph neural network gat
Y a - t - il des cas où sqlcdc surveille plusieurs tables et les associe à une autre? Tout fonctionne dans MySQL
Bigder:34/100 面试感觉挺好的,没有收到录取
Differences and usage scenarios between TCP and UDP
Lecture 4 of Data Engineering Series: sample engineering of data centric AI
SSM 程序集
Looking at the trend of sequence modeling of recommended systems in 2022 from the top paper
MySQL winter vacation self-study 2022 11 (8)
构建库函数的雏形——参照野火的手册
Global and Chinese markets hitting traffic doors 2022-2028: Research Report on technology, participants, trends, market size and share
[robot hand eye calibration] eye in hand
I changed the driver to 5.1.35, but it is still the same error. I can succeed even now, but I will report this every time I do an SQL operation
How to check the lock information in gbase 8C database?
Sword finger offer 29 Print matrix clockwise
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 13
sql表名作为参数传递