当前位置:网站首页>[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 ?


边栏推荐
- [Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 18
- The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
- Blue Bridge Cup group B provincial preliminaries first question 2013 (Gauss Diary)
- Shell script updates stored procedure to database
- Method of changing object properties
- 零基础自学STM32-复习篇2——使用结构体封装GPIO寄存器
- 模板_快速排序_双指针
- [Digital IC manual tearing code] Verilog asynchronous reset synchronous release | topic | principle | design | simulation
- 在线怎么生成富文本
- 【机器人库】 awesome-robotics-libraries
猜你喜欢

爬虫(9) - Scrapy框架(1) | Scrapy 异步网络爬虫框架

一个复制也能玩出花来

2022.02.13

HttpRunnerManager安装(三)-Linux下配置myql数据库&初始化数据

米家、涂鸦、Hilink、智汀等生态哪家强?5大主流智能品牌分析

零基础自学STM32-复习篇2——使用结构体封装GPIO寄存器

ReferenceError: primordials is not defined错误解决

2022年版图解网络PDF

A doctor's 22 years in Huawei

Crawler (9) - scrape framework (1) | scrape asynchronous web crawler framework
随机推荐
在GBase 8c数据库中使用自带工具检查健康状态时,需要注意什么?
有没有sqlcdc监控多张表 再关联后 sink到另外一张表的案例啊?全部在 mysql中操作
Differences and usage scenarios between TCP and UDP
Data preparation
729. My schedule I / offer II 106 Bipartite graph
Qt发布exe软件及修改exe应用程序图标
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 24
Global and Chinese markets for single beam side scan sonar 2022-2028: Research Report on technology, participants, trends, market size and share
技术管理进阶——什么是管理者之体力、脑力、心力
Building the prototype of library functions -- refer to the manual of wildfire
ReferenceError: primordials is not defined错误解决
Li Kou today's question -729 My schedule I
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 18
Paper notes: graph neural network gat
Gifcam v7.0 minimalist GIF animation recording tool Chinese single file version
Formatting occurs twice when vs code is saved
QT release exe software and modify exe application icon
Number conclusion LC skimming review - 1
【无标题】数据库中一条查询SQL执行的过程
Paper notes: limit multi label learning galaxc (temporarily stored, not finished)