如何实现任意矩阵元素整体逆序?现有MATLAB代码问题求助
Hey there! Let's break down why your loop isn't giving you the full reversed matrix, and go through a few ways to fix it—including some cleaner built-in MATLAB methods that will save you from writing loops entirely.
The Problem With Your Current Loop
In your for loop, you're reassigning A to just the current flipped row every time:
[a,b]=size(X); for i=0:a-1 A = [fliplr(X(a-i,:))]; end
This means each iteration overwrites A instead of adding the new flipped row to the existing matrix. By the end of the loop, you only have the last flipped row left.
Solution 1: Fix the Loop
To fix this, initialize A as an empty matrix first, then append each flipped row to it using vertical concatenation (;):
[a,b] = size(X); A = []; % Start with an empty matrix for i = 0:a-1 % Append the flipped row to the bottom of A A = [A; fliplr(X(a-i,:))]; end % If you want the result as a single row vector (like your 3x3 example), add: A = A(:)';
Running this with your test matrix X = [1 2 3; 4 5 6; 7 8 9] will give you the full reversed matrix, and the final line will flatten it into the row [9 8 7 6 5 4 3 2 1].
Solution 2: Use Built-in MATLAB Functions (Better & Faster)
MATLAB has built-in functions that make this way simpler, no loops required. Here are two great options:
Option A: Combine flipud and fliplr
First flip the matrix upside down with flipud, then flip each row left-to-right with fliplr:
X = [1 2 3; 4 5 6; 7 8 9]; B = fliplr(flipud(X));
This gives you the reversed matrix:
9 8 7 6 5 4 3 2 1
If you need it as a single row vector, just flatten it:
B = B(:)';
Option B: Directly Flip the Matrix as a Vector
If you only care about the final flattened reversed row, you can convert the matrix to a column vector, flip it, then transpose back to a row:
B = flip(X(:))';
This skips creating the intermediate reversed matrix and directly gives you [9 8 7 6 5 4 3 2 1] for your test case.
Why Built-in Functions Are Better
For small matrices, loops work fine, but as your matrix gets larger, built-in functions are way more efficient—MATLAB is optimized for these operations, so they'll run faster and use less memory than manual loop concatenation.
内容的提问来源于stack exchange,提问作者anil

