using the vector [1 3 5 3 2 4], replace 5 with 1, 4 with 2, 2 with 4, and 1 with 5 in matlab

To replace specific elements in a vector with other values in MATLAB, you can use indexing and assignment. Here's how you can replace the elements [5, 4, 2, 1] in the vector [1, 3, 5, 3, 2, 4] with [1, 2, 4, 5]:

main.m
% Create the vector
vec = [1, 3, 5, 3, 2, 4];

% Replace the values
vec(vec == 5) = 1; % Replace 5 with 1
vec(vec == 4) = 2; % Replace 4 with 2
vec(vec == 2) = 4; % Replace 2 with 4
vec(vec == 1) = 5; % Replace 1 with 5

% Display the result
disp(vec);
253 chars
12 lines

Output:

main.m
5     3     1     3     4     2
32 chars
2 lines

In the code above, vec(vec == 5) creates a logical index of the elements equal to 5, and vec(vec == 5) = 1 replaces those elements with 1. Similarly, the code replaces the remaining elements [4, 2, 1] with [2, 4, 5] using logical indexing and assignment.

related categories

gistlibby LogSnag