国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Web Front-end JS Tutorial Creating a Web App with MATLAB and the MEAN Stack

Creating a Web App with MATLAB and the MEAN Stack

Feb 19, 2025 pm 01:22 PM

Creating a Web App with MATLAB and the MEAN Stack

Core points

  • MATLAB, a high-level language for technical computing, can be integrated with the MEAN stack to create powerful web applications.
  • MEAN stack consists of MongoDB, Express.js, AngularJS and Node.js, and when used in conjunction with MATLAB, it allows real-time data visualization on the web.
  • The integration process involves using MATLAB's computing power to process data and generate results, which are then displayed on a web application built using the MEAN stack.
  • JSONlab, a free open source JSON encoder/decoder implementation in the MATLAB language, is used to convert MATLAB data to JSON format for use in web applications.
  • Creating a MATLAB Web Application includes creating standalone applications using MATLAB Compiler, creating a web application project in the MATLAB Web App Server, uploading standalone applications to the web application project, and deploying the web application to the user.

MATLAB is a high-level language for technical computing that integrates computing, visualization and programming in an easy-to-use environment where problems and solutions can be expressed in familiar mathematical notation. There are many projects around the world written in MATLAB and developed by millions of scientists and engineers. Various experimental and operational data people obtain from MATLAB can be used to support web applications, but there are some obstacles:

  • MATLAB understands matrix format data, while web applications prefer data in JSON or XML format.
  • Data is usually created and used within the MATLAB program, which limits developers' freedom in saving and using data, etc.

Creating an application is much easier if MATLAB serves data in JSON format and a web application can use this JSON data from MATLAB to create something great.

In this article, we will develop a small demonstration program to demonstrate how to make the MATLAB and MEAN stack work together.

About Web Application

This web application will involve real-time data transfer from MATLAB to the browser. For simplicity, we will transfer the current time from MATLAB and display it on the browser. We will use JSONlab, a toolbox for encoding/decoding JSON files in MATLAB. The web application will be created using the MEAN stack. If you are not familiar with MEAN stack, it is recommended that you read the article "Beginner of MEAN Stack" before continuing.

Introduction to JSONlab

JSONlab is a free open source implementation of JSON encoder/decoder in MATLAB language. It can be used to convert MATLAB data structures (arrays, structures, cells, structure arrays, and cell arrays) into strings in JSON format, or to decode JSON files into MATLAB data.

It gives us access to four functions: loadjson(), savejson(), loadubjson(), and saveubjson(). The last two functions are used to handle the UBJSON format. loadjson() is used to convert JSON strings into related MATLAB objects. In our project, we only use the savejson() function, which converts a MATLAB object (cell, structure, or array) to a JSON string. It can be used as follows:

json = savejson(rootname, obj, filename)
json = savejson(rootname, obj, opt)
json = savejson(rootname, obj, 'param1', value1, 'param2', value2, ...)

Since we have to write the file, we will use the first signature. It returns a JSON string as well as writes the string to the file.

JSONlab installation

To get started, download JSONlab, unzip the archive, and add the path of the folder to the path list of MATLAB using the following command:

addpath('/path/to/jsonlab');

If you want to add this path permanently, you need to type pathtool, browse to the JSONlab root folder and add it to the list. Once finished, you must click Save. Then, run rehash in MATLAB and type which loadjson. If you see the output, it means JSONlab is installed correctly.

MATLAB code

We need the current time, so we will use the clock command. It returns a six-element date vector containing the current date and time in the format [Year, Month, Day, Hours, Minutes, Seconds]. To get the time repeatedly, we put the clock command in an infinite while loop. Therefore, we will keep getting the real-time data until the script execution is terminated using Ctrl C on the MATLAB command window.

The following code implements this idea:

format shortg;
y=0;
while y == 0
    % c = [year month day hour minute seconds]
    c=clock;
    % 將每個值四舍五入為整數(shù)
    c=fix(c);
    x.clock=c;
    % 訪問c的第4列,即小時
    x.hours=c(:,4);
    % 訪問c的第5列,即分鐘
    x.minutes=c(:,5);
    % 訪問c的第6列,即秒
    x.seconds=c(:,6);
    % 將x轉(zhuǎn)換為JSON并寫入matlabData.json
    savejson('',x,'data/matlabData.json');
end

In our projects, we focus on hours, minutes, and seconds. The fix(c) function used in the above code rounds all elements of the matrix to the nearest integer. To get hour data, we need the value of column 4 of the matrix, so we use the command c(:,4). Using the same method, we retrieve minutes and seconds.

We will send the clock and some separate variables to the web application separately to display the conversion of different data types from the MATLAB object to JSON. While the clock data will be converted to an array, the values ??of hours, minutes and seconds will be converted to numbers, which we will see later.

In our project, we will use the savejson() function to convert and write variable x using JSON format and write it to the file matlabData.json. For simplicity, the rootname parameter will be an empty string.

Use the previous code, we complete all the required MATLAB code. Now, once we run the script, we can observe that the JSON file is created in the data folder and that the data in the file will be updated automatically and constantly. Examples of JSON file content are as follows:

{
   "hours": 19,
   "minutes": 28,
   "seconds": 28,
   "clock": [2015,5,27,19,28,28]
}

We will monitor this file and use Node.js to read the latest data. Now let's start building a web application.

Web Application

Now that our MATLAB data has been converted to JSON and stored in a file, we can read this file independently and get the data by monitoring its changes. This operation has nothing to do with MATLAB. In the rest of this article, I'll assume you understand socket.io and the MEAN stack, even if we only use some of their basic concepts.

Let's start writing web applications.

Create package.json file

To start our application, let's define the dependencies of the project. To do this, we will create a package.json file as follows:

json = savejson(rootname, obj, filename)
json = savejson(rootname, obj, opt)
json = savejson(rootname, obj, 'param1', value1, 'param2', value2, ...)
After creating the file, run

in the root folder of the project to install all dependencies. If you are not familiar with npm, it is recommended that you read the "NPM Getting Started Guide - Node Package Manager". npm install

Server side code This part of the code involves the use of Node.js, Express, and MongoDB. The operations performed by the server include:

Provided
    File
  • index.html Monitor and read data in JSON files
  • Save data to database using MongoDB
  • Send data to browser using socket.io
  • We will create a file named
in the root folder where we will write the code required for all the functions described.

server.jsWe use Express to provide static files:

Whenever a request is sent to
addpath('/path/to/jsonlab');
, a

file stored in the / directory will be provided. app index.htmlTo monitor any changes to the file, we use

, and to read the file every time it changes, we use

. Once a change is detected, the file is read and the data is retrieved. The whole process is completed using the following code: fs.watch() fs.readFile()

When a connection is established with the client and starting to fetch data, we will do two things:
format shortg;
y=0;
while y == 0
    % c = [year month day hour minute seconds]
    c=clock;
    % 將每個值四舍五入為整數(shù)
    c=fix(c);
    x.clock=c;
    % 訪問c的第4列,即小時
    x.hours=c(:,4);
    % 訪問c的第5列,即分鐘
    x.minutes=c(:,5);
    % 訪問c的第6列,即秒
    x.seconds=c(:,6);
    % 將x轉(zhuǎn)換為JSON并寫入matlabData.json
    savejson('',x,'data/matlabData.json');
end

Send data to the browser using socket.io's
    function
  1. emit()Save data to MongoDB using mongoose middleware
  2. To perform the second operation, we create a schema of the data and then create a model based on that schema. This is done using the code shown below:

In the last statement of the previous code segment, we create a model based on the defined pattern. The first parameter passed to the function is the singular name of the set to which our model belongs. Mongoose automatically assigns plural names to the collection. Therefore, here
{
   "hours": 19,
   "minutes": 28,
   "seconds": 28,
   "clock": [2015,5,27,19,28,28]
}
is a model of the

collection. appData appDatasWhen we get new data, we will use the latest data to create a new instance of the schema and save it to the database using the

method. This instance is called a document. In the following code,

is a document. save() savingDataThe final code for this part is as follows:

json = savejson(rootname, obj, filename)
json = savejson(rootname, obj, opt)
json = savejson(rootname, obj, 'param1', value1, 'param2', value2, ...)

We use try and catch to prevent the application from crashing. If we don't use it, and the JSON.parse caused unexpected user input errors due to the rapid change, the application may crash. This is what we want to avoid!

Also note that please make sure the MongoDB server is running, otherwise the application will crash.

Client code

In this section, we will create a simple static HTML page. When new data is received through socket.io, we will update the data displayed on the page. This data can also be used to create real-time charts.

The following is the simple code for the index.html file:

addpath('/path/to/jsonlab');
The

ngCloak directive is used to prevent the browser from briefly displaying the original (uncompiled) form of AngularJS template when the application is loading.

Run the application

Before starting the Node.js server, we need to make sure that the MATLAB code and the MongoDB server are running. To run the MongoDB server, you need to execute the command mongod on the terminal. To run the Node.js server, you must execute the command node server.js in the root directory of the project folder.

The static page showing the current time will be provided in 127.0.0.1:3000.

Conclusion

In this article, we use the MEAN stack to create a web application that gets data in JSON format from the MATLAB program. Data is converted with the help of JSONlab. The data is then sent to the browser using socket.io, so changes on the browser are reflected in real time. The full source code for this demo is available on GitHub.

I hope you enjoyed this article and look forward to reading your comments.

(The FAQs section is recommended to handle it separately due to the length of the article. Key questions and answers can be extracted and briefly summarized or reorganized as needed.)

The above is the detailed content of Creating a Web App with MATLAB and the MEAN Stack. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java vs. JavaScript: Clearing Up the Confusion Java vs. JavaScript: Clearing Up the Confusion Jun 20, 2025 am 12:27 AM

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

Javascript Comments: short explanation Javascript Comments: short explanation Jun 19, 2025 am 12:40 AM

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

How to work with dates and times in js? How to work with dates and times in js? Jul 01, 2025 am 01:27 AM

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

Why should you place  tags at the bottom of the ? Why should you place tags at the bottom of the ? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScript vs. Java: A Comprehensive Comparison for Developers JavaScript vs. Java: A Comprehensive Comparison for Developers Jun 20, 2025 am 12:21 AM

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

What is event bubbling and capturing in the DOM? What is event bubbling and capturing in the DOM? Jul 02, 2025 am 01:19 AM

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

JavaScript: Exploring Data Types for Efficient Coding JavaScript: Exploring Data Types for Efficient Coding Jun 20, 2025 am 12:46 AM

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

How can you reduce the payload size of a JavaScript application? How can you reduce the payload size of a JavaScript application? Jun 26, 2025 am 12:54 AM

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch

See all articles