Concatenating a cell array
11 views (last 30 days)
Show older comments
Given: A cell array with names where names={'Harry','Xavier','Sue'};
Find: How to concantenate a '1' at the end of each character array using a for-loop and the strcat function, among others.
Issue: I am utterly confused on what this is asking and why. I am assuming it's just practice concatenating but I have only really done this in excel.
My solution: Being unfamiliar with this in MATLAB, I don't really know where to start but I tried:
CAT=strcat(ones(Names));
% Got an error here: Size inputs must be numeric.
So If I can't use the ones function, how else can I approach this for that part of the question?
4 Comments
Accepted Answer
Rik
on 15 Apr 2024
The assignment tells you to use a for loop. So even if it can be solved without one, let's do it. But before we can do that, we need to figure out what we want to do in each iteration. That's easy: we want to do something with each element, so let's write a loop that helps us do that:
names = {'Harry','Xavier','Sue'};
for n=1:numel(names)
end
So now we have a loop. The next step is to add '1' to each element. While we could use square brackets, we can use the strcat function as well. If you don't know what to do, you need to read the documentation for this function:
help strcat % use doc instead of help to open the documentation browser
After reading this (in the documentation browser), you can simply adapt the example given:
strcat(names{n},'1')
% note the {} to get the content of the cell
% () would give you the cell itself, not the contents
The final piece of the puzzle is to store it back in the original array:
names = {'Harry','Xavier','Sue'};
for n=1:numel(names)
names{n} = strcat(names{n},'1');
end
names
If you want to be a smart-ass, you can satisfy the requirement of a for loop AND vectorize your code. Your teacher will either love you or hate you.
names = {'Harry','Xavier','Sue'};
for n=1
names = strcat(names,'1');
end
names
3 Comments
Stephen23
on 16 Apr 2024
"Is there a way to use a for-loop to concatenate the '1' at the end WITHOUT using the strcat function in the loop?"
Of course. This is MATLAB, which you should always remember is based on arrays, so some array operations could do something similar, e.g. indexing or concatenation:
names = {'Harry','Xavier','Sue'};
for k = 1:numel(names)
names{k}(end+1) = '1'; % indexing
names{k} = [names{k},'2']; % concatenation
end
names
The name MATLAB comes from "MATrix LABoratory": thinking in terms of matrices and arrays helps to use MATLAB.
More Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices 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!