当前位置:网站首页>[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
end
effect :
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);
end
Running 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 ?
边栏推荐
- 2345文件粉碎,文件强力删除工具无捆绑纯净提取版
- [Digital IC manual tearing code] Verilog asynchronous reset synchronous release | topic | principle | design | simulation
- 【MySQL 15】Could not increase number of max_open_files to more than 10000 (request: 65535)
- 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
- 在线怎么生成富文本
- Multiple solutions to one problem, asp Net core application startup initialization n schemes [Part 1]
- Reset nodejs of the system
- Shell脚本更新存储过程到数据库
- Follow the mouse's angle and keyboard events
- 力扣今日題-729. 我的日程安排錶 I
猜你喜欢
[community personas] exclusive interview with Ma Longwei: the wheel is not easy to use, so make it yourself!
Minecraft 1.16.5 biochemical 8 module version 2.0 storybook + more guns
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 18
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 9
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 23
"Hands on learning in depth" Chapter 2 - preparatory knowledge_ 2.5 automatic differentiation_ Learning thinking and exercise answers
vs code保存时 出现两次格式化
在线怎么生成富文本
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 21
Initial understanding of pointer variables
随机推荐
怎么检查GBase 8c数据库中的锁信息?
"Hands on learning in depth" Chapter 2 - preparatory knowledge_ 2.5 automatic differentiation_ Learning thinking and exercise answers
There are so many giants, why should we independently develop POS store cashier system?
HttpRunnerManager安装(三)-Linux下配置myql数据库&初始化数据
事故指标统计
Microsoft speech synthesis assistant v1.3 text to speech tool, real speech AI generator
Initial understanding of pointer variables
729. My schedule I / offer II 106 Bipartite graph
Template_ Find the reverse pair of permutations_ Sort based on merge
A doctor's 22 years in Huawei
DDoS attacks - are we really at war?
爬虫(9) - Scrapy框架(1) | Scrapy 异步网络爬虫框架
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 23
[robot library] awesome robots Libraries
Formatting occurs twice when vs code is saved
力扣今日題-729. 我的日程安排錶 I
Network Security Learning - Web vulnerabilities (Part 1)
ReferenceError: primordials is not defined错误解决
Reset nodejs of the system
[untitled] a query SQL execution process in the database