You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现N×1列向量中10与25的数值互换?

Swap 10 and 25 in a Column Vector (MATLAB)

Hey Alan, let's get this sorted out! You're trying to swap all instances of 10 with 25 (and vice versa) in an N×1 column vector, but your current code has a few small issues preventing it from working. Let's break down the problem and fix it with clean, efficient solutions.

First, let's look at why your existing code didn't work:

  • Your first approach: Using find() gives you the indices of elements matching 10 or 25, but your for loop structure doesn't properly use those indices to assign new values. The logic you wrote doesn't map to valid MATLAB syntax for modifying elements by index.
  • Your loop code:
    • for B = 1:size(A) is incorrect because size(A) returns a 2-element array (e.g., [7,1] for a 7×1 vector), so your loop would run twice instead of 7 times. You need size(A,1) to target the number of rows.
    • if A == 10 checks if the entire vector equals 10, not the single element at position B. You need to access A(B) to work with individual elements.

Solution 1: Vectorized Math (Simplest & Fastest)

Since your vector only contains 10 and 25, notice that their sum is 35. Subtracting each element from 35 will directly swap the values:

A = [10; 25; 25; 10; 25; 25; 10];
A_swapped = 35 - A;

This is the most MATLAB-idiomatic approach—no loops, no conditional checks, just a single operation that works instantly even for large vectors.

Solution 2: Logical Indexing (Explicit & Flexible)

If you prefer a more explicit approach (useful if you might add other values later), use logical indices to target elements and assign new values. Just make sure to precompute the indices first to avoid overwriting values mid-operation:

A = [10; 25; 25; 10; 25; 25; 10];
% Precompute indices for 10s and 25s
is_10 = A == 10;
is_25 = A == 25;

% Swap values
A(is_10) = 25;
A(is_25) = 10;

If you tried to do this without precomputing indices (e.g., first set 10s to 25, then 25s to 10), you'd accidentally overwrite the newly set 25s back to 10—precomputing avoids that.

Solution 3: Fixed Loop Approach

If you specifically want to use a loop (for learning purposes), here's how to correct your code:

A = [10; 25; 25; 10; 25; 25; 10];
% Loop over each row in the column vector
for B = 1:size(A, 1)
    if A(B) == 10
        A(B) = 25;
    elseif A(B) == 25
        A(B) = 10;
    end
end

This loop iterates over each element individually, checks its value, and swaps it accordingly.


内容的提问来源于stack exchange,提问作者Alan De Moin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:23:06