0

I have written a matlab function ;now as I simulate it the following error occurs

h(n) = (str.(n));

??? Attempt to reference field of non-structure array.; I could not figure it out . Can any one help ?

function control(varargin)

str =  {
    'violet';
    'indigo';
    'blue';
    'green';
    'yellow';
    'orange';
    'red';
    };

N = length(str);
h = zeros(N,1);
for n =1:N
    h(n) = str.(n);
end

What is the problem with statement h(n)? I want to store str elements in h(n). I also want to pass values to vibgyor from another function. How do I call it from other function?

2 Answers 2

1

Variable str is not a structure, it is an array of strings. You can convert it as below

str =  {
    'violet';
    'indigo';
    'blue';
    'green';
    'yellow';
    'orange';
    'red';
    };

N = length(str);
h = zeros(N,6);

for n =1:N
    X=cell2mat(str(n));

    for m=1:length(X)
        h(n,m) = X(m);
    end;
end

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

Comments

1

As stated str is not a structure so to reference the nth element you would just remove the dot on this line:

 h(n) = str(n);

However that would give you this error:

??? The following error occurred converting from cell to double: Error using ==> double Conversion to double from cell is not possible.

That is because you initialized h to zeros and you are trying to make it a cell array. So you should change to the following:

str =  {
    'violet';
    'indigo';
    'blue';
    'green';
    'yellow';
    'orange';
    'red';
    };

N = length(str);
h = cell(N,1);
for n =1:N
    h(n) = str(n);
end

However, if all you are doing is assigning h to str why would you not skip the for loop and just do this

h = str;

Comments

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.