技术咨询:MATLAB变量取值与矩阵行删除,如何得到矩阵B
Hey there! Let's tackle your MATLAB questions one by one—first about checking variable values, then how to strip out specific rows from a matrix to get your target matrix B. I'll keep it practical with code examples so you can test it right away.
There are a few straightforward ways to inspect what your variables hold:
- Direct command line lookup: Just type the variable name and hit enter. MATLAB will print its full content, along with details like dimensions and data type. For example, if you have a matrix
myMatrix, runmyMatrixto see it. - Use
disp()for clean output: If you don't want the variable name displayed alongside the content, usedisp(myVariable). This is great for quick, uncluttered checks. - Workspace panel: Look at the Workspace tab on the right side of the MATLAB interface. It lists all active variables—click any one to open the Variable Editor, which is perfect for browsing large matrices or complex structures like cell arrays.
- Check specific elements/ranges: To zoom in on a part of your variable, use indexing. For a matrix
A,A(3,2)gives you the value at row 3, column 2;A(1:4,:)shows the first 4 rows of all columns.
The approach depends on whether you know the exact rows to delete, or need to filter based on a condition. Here are the most common scenarios:
Scenario 1: Delete specific, known rows
Suppose you have a matrix A and want to remove rows 2 and 5 to get B:
% Example original matrix A = [1 2 3; 4 5 6; 7 8 9; 10 11 12; 13 14 15]; % Define rows to remove as a vector rowsToDelete = [2, 5]; % Create B by removing those rows B = A; B(rowsToDelete, :) = []; % Assigning empty array removes the rows
MATLAB automatically collapses the matrix when you set rows to []—no extra steps needed!
Scenario 2: Delete rows based on a condition
Say you want to remove all rows where the value in column 1 is greater than 10. You can use logical indexing to filter the rows you want to keep:
A = [5 2; 12 7; 8 4; 15 9]; % Keep only rows where column 1 is <=10 B = A(A(:, 1) <= 10, :);
The expression A(:,1) <=10 creates a logical vector where each entry is true if the row should be kept, false if it should be deleted. This is the most efficient way to filter rows conditionally.
Scenario 3: Delete duplicate rows
If your matrix has duplicate rows and you want B to have only unique entries, use the unique() function:
A = [1 2; 3 4; 1 2; 5 6]; % Get unique rows while preserving their original order [B, ~, ~] = unique(A, 'rows', 'stable');
The 'rows' flag tells MATLAB to compare entire rows, and 'stable' ensures the order matches the first occurrence of each unique row in A.
内容的提问来源于stack exchange,提问作者Ali Dr

