3

If I have a class like this:

classdef Person
  properties
    Name
    Age
    Weight
  end
  methods
    function obj = Person(name, age, weight)
      obj.Name = name;
      obj.Age = age;
      obj.Weight = weight;
    end
  end
end

And attempt to create a vector of just the names like this:

angus = Person("Angus Comber", 40, 73);
lisa  = Person("Lisa Comber", 39, 60);
jack  = Person("Jack Comber", 4, 15);
family = [angus lisa jack];

just_names = [family(:).Name];

Then the result is what I want:

>> just_names
just_names = 
  1×3 string array
    "Angus Comber"    "Lisa Comber"    "Jack Comber"

But if I create the Person's like this:

angus = Person('Angus Comber', 40, 73);
lisa  = Person('Lisa Comber', 39, 60);
jack  = Person('Jack Comber', 4, 15);
family = [angus lisa jack];

just_names = [family(:).Name];

Then I get:

>> just_names
just_names =
    'Angus ComberLisa ComberJack Comber'

Unfortunately, the input names in my sample are all chars (not strings). So given the char input, how can I edit the code to get the array I want?

1 Answer 1

6

It may not be quite what you want because it doesn't result in a vector of strings but changing the final line of the code to

just_names = {family(:).Name};

with the curly braces, will give the result

just_names =

  1×3 cell array

    {'Angus Comber'}    {'Lisa Comber'}    {'Jack Comber'}

So it avoids appending the characters of the names together.

Sign up to request clarification or add additional context in comments.

1 Comment

Or string({family(:).Name}) to get the result as an array of strings. @Angus But then it may be better to use obj.Name = string(name); in the class definition to make sure that the names are always stored as strings, regardless of whether they are provided as strings or as char vectors

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.