Scalar structure required for this assignment - For Loop

33 ビュー (過去 30 日間)
Emily
Emily 2022 年 6 月 2 日
編集済み: Stephen23 2022 年 6 月 2 日
Hi, I was looking at this example below, and was wondering if it was possible to solve the error while keeping the for loop.
myStruct=repmat(struct('text1',0),10,1);
myarray = [
1 2 3 4 5 6 7 8 9 10];
for j = 1:10 mystruct(j).text11 = myarray(j); end
mystruct.text11 = myarray
  4 件のコメント
Stephen23
Stephen23 2022 年 6 月 2 日
Emily's incorrectly posted "Answer" moved here:
For some reason I'm getting errors when I try to comment below your comment Walter.
When I try running that code it gives out this output.
Scalar structure required for this assignment
I think the original poster of the question wanted to have 10x1 struct with first field being ten 0s and second being 1-10. The poster solved it by turning myarray into cells straight, but I was wondering how to use for loop to solve it.
Stephen23
Stephen23 2022 年 6 月 2 日
編集済み: Stephen23 2022 年 6 月 2 日
"I think the original poster of the question wanted to have 10x1 struct with first field being ten 0s and second being 1-10."
Correct.
"The poster solved it by turning myarray into cells straight..."
... and also by using a loop, which is included in their post.
The line of code which causes the error is totally unrelated to the loop.
"...but I was wondering how to use for loop to solve it."
They already showed such a loop. Why not try the loop that they already showed?
Perhaps you are getting confused by the line of code which throws an error (and is rather the point of that post), but which is not part of the loop. Here is their code with the one unrelated following line of code removed, the variable names corrected, and using standard alignment:
mystruct = repmat(struct('text1',0),10,1);
myarray = 1:10;
for j = 1:10
mystruct(j).text11 = myarray(j);
end
Checking:
mystruct
mystruct = 10×1 struct array with fields:
text1 text11
mystruct.text1
ans = 0
ans = 0
ans = 0
ans = 0
ans = 0
ans = 0
ans = 0
ans = 0
ans = 0
ans = 0
mystruct.text11
ans = 1
ans = 2
ans = 3
ans = 4
ans = 5
ans = 6
ans = 7
ans = 8
ans = 9
ans = 10
So far everything seems to be working as expected.

サインインしてコメントする。

回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by