Input to Struct Array

3 views (last 30 days)
Pamela
Pamela on 1 Nov 2012
I have been playing around with structs in Matlab all day and can't seem to grasp it. I have this code:
mystruct.color = 'red', 'green', 'red', 'red'; mystruct.angles = [30,60,90,180]; mystruct.row = [];
for i=1:3, mystruct.row[i] = input('Enter row: '); end
Where I want to input values for a row and have it stored in the row field in the mystruct struct but I keep getting this error:
Error: File: StructTest.m Line: 7 Column: 19 Unbalanced or unexpected parenthesis or bracket.
What I ultimately want to do is scan an image matrix and capture the rows of certain pixels but I need to understand this first.
Any help would be greatly appreciated.

Answers (3)

Image Analyst
Image Analyst on 1 Nov 2012
You need to use parentheses, not brackets: mystruct.row(i) not mystruct.row[i]
Secondly
mystruct.color = 'red', 'green', 'red', 'red';
probably doesn't do what you think it does. It does not make the color member of mystruct into a cell array with 4 elements. It assigns a string element and then basically does nothing with the string literals you define, so it's the same as these 4 completely separate lines:
mystruct.color = 'red';
'green';
'red';
'red';
Perhaps you want
mystruct.color = {'red', 'green', 'red', 'red'}; % Enclosed in braces
I have no idea what you want.

Pamela
Pamela on 1 Nov 2012
Thanks for you reply.
I want to be able to enter values to the field in a for loop.
When I run:
for i=1:3, mystruct.row(i) = input('Enter row: '); end
I get:
Enter row: 2 Scalar structure required for this assignment.
Error in StructTest (line 7) mystruct.row(i) = input('Enter row: ');
But I want to be able to enter 3 values and have it be referenced as:
mystruct.row(1) = 1; (or any arbitrary values) mystruct.row(2) = 2; mystruct.row(3) = 3;
Do I have the wrong understanding on how Matlab structs work?

Andrei Bobrov
Andrei Bobrov on 1 Nov 2012
mystruct.color = {'red', 'green', 'red', 'red'};
mystruct.angles = [30,60,90,180];
for i1=1:3
mystruct.row(i1) = input('Enter row: ');
end

Categories

Find more on Interactive Control and Callbacks in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!