assign value for field in a struct using a loop

조회 수: 4 (최근 30일)
Hannah
Hannah 2014년 5월 4일
댓글: Hannah 2014년 5월 5일
Hi
am trying to save variables into structure using a loop but i have a problem assigning fieldnames and values so what i did was
b = 1:50;
field = ['Contrast_' num2str(b) ] yet i dont know how to assign the value of Contrast to this field.
i tried something like value = (field) or value = [field] but it doesn't retrieve the value of the variable.
what am doing is measuring contrast for each slice for an image in a loop so it is important for me to relate the slice number to the contrast value but i also want to save all of the contrast values in struct in the end where the field name is the contrast_'sliceNumber'.
any help is appreciated.
thanks Hannah
  댓글 수: 2
Jan
Jan 2014년 5월 4일
You write of "structures" - do you mean "structs"? Your code does not contain structs or fields.
Hannah
Hannah 2014년 5월 5일
yes i mean struct. and i didnt put the complete code because it is very long and i needed help with using field names and values in a loop.
Hannah

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2014년 5월 4일
As Image Analyst has written already, hiding an index in teh field name is a bad idea:
for k = 1:10
S.(sprintf('Contrast_%d', k)) = rand;
end
It is much better to use an array:
S.Contrast = zeros(1, 10);
for k = 1:10
S.Contrast(k) = rand;
end

추가 답변 (1개)

Image Analyst
Image Analyst 2014년 5월 4일
This is not advised. Read the FAQ: http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F You should use one field that is an array, not tons of fields with different names.
  댓글 수: 2
Hannah
Hannah 2014년 5월 5일
Thank you for your help. the issue is that am measuring many parameters for each image i have for multiple data sets and i started by creating a cell array but it became difficult to find what i needed easily so i tried saving all the parameters i measured in each slice in one struct under different field names.
Image Analyst
Image Analyst 2014년 5월 5일
That should not be the case. In fact it should be the opposite. What you want to do is more complicated, as you know because you have to ask us. Jan gave you the code. It's not difficult at all - how much simpler can it be?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by