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


边栏推荐
- Sword finger offer 29 Print matrix clockwise
- Lecture 4 of Data Engineering Series: sample engineering of data centric AI
- 继承的构造函数
- [Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 8
- SSM assembly
- "Hands on learning in depth" Chapter 2 - preparatory knowledge_ 2.5 automatic differentiation_ Learning thinking and exercise answers
- [Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 7
- Redis delete policy
- ReferenceError: primordials is not defined错误解决
- Force buckle 146 LRU cache
猜你喜欢
![[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 23](/img/72/a80ee7ee7b967b0afa6018070d03c9.jpg)
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 23

3D drawing ()

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
![[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 20](/img/d5/4bce239b522696b5312b1346336b5f.jpg)
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 20

Minecraft 1.16.5 biochemical 8 module version 2.0 storybook + more guns

在线怎么生成富文本

【无标题】数据库中一条查询SQL执行的过程
![[untitled] a query SQL execution process in the database](/img/de/700ee20934fc2cd4a019f761148ef9.png)
[untitled] a query SQL execution process in the database

力扣今日題-729. 我的日程安排錶 I

Déduisez la question d'aujourd'hui - 729. Mon emploi du temps I
随机推荐
Pat grade a 1033 to fill or not to fill
HDU_ p1237_ Simple calculator_ stack
零基础自学STM32-野火——GPIO复习篇——使用绝对地址操作GPIO
A doctor's 22 years in Huawei
Déduisez la question d'aujourd'hui - 729. Mon emploi du temps I
模板_求排列逆序对_基于归并排序
Accident index statistics
2022 eye health exhibition, vision rehabilitation exhibition, optometry equipment exhibition, eye care products exhibition, eye mask Exhibition
2020.02.11
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
深度解析链动2+1模式,颠覆传统卖货思维?
力扣今日题-729. 我的日程安排表 I
A copy can also produce flowers
从顶会论文看2022年推荐系统序列建模的趋势
3D drawing ()
Qt发布exe软件及修改exe应用程序图标
继承的构造函数
Httprunnermanager installation (III) - configuring myql Database & initialization data under Linux
JS events (add, delete) and delegates
Data preparation