How would I replace a string of numbers with more numbers using for and if statements?
Show older comments
Here is my code so far. I'm trying to make it so that if the number is "1" in the string, it replaces it with five zeros. If the number is "2" in the string it replaces that with 5 ones, and if the number is "3" in the string, it replaces it with 5 twos and make that all a different string of numbers called d. The end should look like this: d = [0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,2,2,2,2,2]. I really need help, I am awful with matlab.
if true
t = [1,2,1,2,1,3];
% For Loop
for n = 1:length(t)
if t(n) == 1
d(n) = 0,0,0,0,0;
elseif t(n) == 2
d(n) = 1,1,1,1,1;
else t(n) == 3
d = 2,2,2,2,2;
end
end
end
Accepted Answer
More Answers (1)
Tyler Johns
on 3 Nov 2018
Keep in mind when programming there is usually more than one way to accomplish your goal. Here is an additional solution. This may not be the most efficient way since the size of vector d changes every loop iteration but it is still a solution nonetheless.
t = [1 2 1 2 1 3];
d=[]; % create empty vector d
for n = 1:length(t)
if t(n)==1
d = [d 0 0 0 0 0]; %add new numbers to end of vector d
elseif t(n)==2
d = [d 1 1 1 1 1];
elseif t(n)==3
d = [d 2 2 2 2 2];
end
end
disp(d)
4 Comments
Jacob Roach
on 3 Nov 2018
Tyler Johns
on 3 Nov 2018
What you are actually doing when you put d at the beginning of the vector is saying I'm going to create a new vector d that includes all of the contents of the old vector d plus add on the rest of the numbers at the end. If you didn't place d as the first entry it would just completely replace it everytime so at the end the d vector would only contain 5 of the same number. I encourage you to erase the d and run the code and see what happens. I do not have Discord but will be happy to answer another question if I can.
Jacob Roach
on 3 Nov 2018
Stephen23
on 3 Nov 2018
Follow madhan ravi's answer: it shows good practice: a preallocated cell array to store the intermediate arrays.
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!