Free MATLAB MATLAB Environment and Syntax Questions and Answers — Questions and Answers
Question 1: Which of the following is an invalid variable name in MATLAB?
- my_variable
- variable123
- 2start_variable (Correct answer)
- _another_variable
Correct answer: 2start_variable
In MATLAB, a valid variable name must start with a letter, followed by any combination of letters, digits, or underscores. The name '2start_variable' is invalid because it begins with a digit.
Question 2: A user wants to remove all variables from the Workspace and clear the text from the Command Window. Which combination of commands achieves this?
- clc; close all
- clear; clc (Correct answer)
- clear all; close
- remove all; clc
Correct answer: clear; clc
The 'clear' command removes all variables from the current workspace. The 'clc' command clears all text from the Command Window, providing a 'clean screen'. The combination 'clear; clc' performs both of the desired actions.
Question 3: In the MATLAB Desktop Environment, which window is primarily used for writing, editing, and saving multi-line scripts and functions that can be executed as a whole?
- Workspace
- Command History
- Editor (Correct answer)
- Command Window
Correct answer: Editor
The Editor is the component of the MATLAB environment designed for writing, editing, saving, and debugging scripts and function files (.m files). The Command Window is for executing single-line commands interactively.
Question 4: A user executes the following code in a new MATLAB session: x = 1:5; y = x(end) + x(1); What is the value of 'y' in the Workspace?
- An error occurs
- 6 (Correct answer)
- 5
- 1
Correct answer: 6
The expression 'x = 1:5' creates a vector [1, 2, 3, 4, 5]. In MATLAB, array indexing starts at 1. The 'end' keyword, when used for indexing, refers to the last element of an array. Therefore, x(end) is 5 and x(1) is 1. The variable 'y' is assigned the sum of these two values, which is 5 + 1 = 6.
Question 5: How do you start a multi-line block comment in a MATLAB script?
- //
- /*
- %%
- %{ (Correct answer)
Correct answer: %{
To create a block comment that spans multiple lines, you begin the block with '%{' and end it with '%}'. The '%%' syntax is used to create runnable code sections, and a single '%' comments out the rest of a single line.
Question 6: A user defines a 3x3 matrix `A = magic(3);`. Which command will correctly extract the entire second row of this matrix?
- A(2)
- A(:, 2)
- A(2, :) (Correct answer)
- A(row=2)
Correct answer: A(2, :)
In MATLAB matrix indexing, the format is `matrix(row, column)`. To select all elements in a dimension, you use the colon operator ':'. Therefore, `A(2, :)` selects the elements from the second row and all columns.
Which of the following is an invalid variable name in MATLAB?