# How do I replace elements in a vector with other vectors?

3 views (last 30 days)
Cai Chin on 30 Dec 2020
Answered: Image Analyst on 30 Dec 2020
Hi, I am currently trying to replace the elements in a vector called 'seq1' with other vectors. seq1 has 12 numbers ranging from 1 to 9 and I am trying to replace each number with vectors of other numbers as follows:
seq1 = [1 2 3 4 5 6 7 8 9 2 4 5];
rectColor1 = [0.1 0.1 0.1];
rectColor2 = [0.15 0.15 0.15];
rectColor3 = [0.22 0.22 0.22];
rectColor4 = [0.30 0.30 0.30];
rectColor5 = [0.40 0.40 0.40];
rectColor6 = [0.55 0.55 0.55];
rectColor7 = [0.7 0.7 0.7];
rectColor8 = [0.85 0.85 0.85];
rectColor9 = [1 1 1];
for i = 1:numel(seq1)
if seq1(i) == 1
seq1(i) = rectColor1;
elseif seq1(i) == 2
seq1(i) = rectColor2;
elseif seq1(i) == 3
seq1(i) = rectColor3;
elseif seq1(i) == 4
seq1(i) = rectColor4;
elseif seq1(i) == 5
seq1(i) = rectColor5;
elseif seq1(i) == 6
seq1(i) = rectColor6;
elseif seq1(i) == 7
seq1(i) = rectColor7;
elseif seq1(i) == 8
seq1(i) = rectColor8;
elseif seq1(i) == 9
seq1(i) = rectColor9;
end
end
However, I keep getting the following error:
Unable to perform assignment because the left and right sides have a different number of elements.
How do I resolve this issue? Thanks in advance.

Ameer Hamza on 30 Dec 2020
Don't create variable name dynamically like rectColor1, rectColor2, .. It always makes code more difficult. Following shows how you can easily solve the problem using a cell array
seq1 = [1 2 3 4 5 6 7 8 9 2 4 5];
rectColor{1} = [0.1 0.1 0.1];
rectColor{2} = [0.15 0.15 0.15];
rectColor{3} = [0.22 0.22 0.22];
rectColor{4} = [0.30 0.30 0.30];
rectColor{5} = [0.40 0.40 0.40];
rectColor{6} = [0.55 0.55 0.55];
rectColor{7} = [0.7 0.7 0.7];
rectColor{8} = [0.85 0.85 0.85];
rectColor{9} = [1 1 1];
seq1 = cell2mat(rectColor(seq1))

Image Analyst on 30 Dec 2020
Perhaps this is what you want, where there are 3 rows in the output where each column has the color identified by seq1:
seq1 = [1 2 3 4 5 6 7 8 9 2 4 5]; % 1-by-12
% Define 9 different colors:
rectColor = zeros(3, 9); % Initialize to 3x9 shape.
rectColor(:, 1) = [0.1 0.1 0.1]';
rectColor(:, 2) = [0.15 0.15 0.15]';
rectColor(:, 3) = [0.22 0.22 0.22]';
rectColor(:, 4) = [0.30 0.30 0.30]';
rectColor(:, 5) = [0.40 0.40 0.40]';
rectColor(:, 6) = [0.55 0.55 0.55]';
rectColor(:, 7) = [0.7 0.7 0.7]';
rectColor(:, 8) = [0.85 0.85 0.85]';
rectColor(:, 9) = [1 1 1]';
output = zeros(3, length(seq1)); % Initialize to proper shape, 3-by-12.
% For each column paste in the proper color:
output = rectColor(:, seq1)
You get a 3-by-12 matrix where each column is a color:
output =
Columns 1 through 9
0.1 0.15 0.22 0.3 0.4 0.55 0.7 0.85 1
0.1 0.15 0.22 0.3 0.4 0.55 0.7 0.85 1
0.1 0.15 0.22 0.3 0.4 0.55 0.7 0.85 1
Columns 10 through 12
0.15 0.3 0.4
0.15 0.3 0.4
0.15 0.3 0.4