Assignment of variables by comma separated lists
이전 댓글 표시
I have some trouble understanding the behaviour of comma separated lists. Consider
A = struct('number', cell(1, 5));
If I want to assign numbers from 1 to 5, I have to introduce an auxiliary cell array:
numbers=num2cell(1:5);
[A.number]=numbers{:};
The direct way
[A.number]=1,2,3,4,5;
doesn't work although numbers{:} and 1,2,3,4,5 return the exact same result when entered at the command line. Why is that? And is there a more efficient way to assign a vector or an array of values to a struct than using an auxiliary cell array?
채택된 답변
추가 답변 (1개)
Bruno Luong
2021년 4월 7일
Use deal
>> A = struct('number', cell(1, 5));
>> A
A =
1×5 struct array with fields:
number
>> n=1:5;
>> c=num2cell(n);
>> [A.number]=deal(c{:})
A =
1×5 struct array with fields:
number
>> A.number
ans =
1
ans =
2
ans =
3
ans =
4
ans =
5
>>
댓글 수: 5
broken_arrow
2021년 4월 7일
Bruno Luong
2021년 4월 7일
편집: Bruno Luong
2021년 4월 7일
In this case no, but yo could look at the doc of deal for cases where directly using cell does not work.
In older MATLAB, the syntax
[...] = c{:}
throws an error. The new syntax is just an convenient extension of deal.
Personaly I never use those shortcut syntax in my code, it is as dangerous as length(); squeeze, etc...
broken_arrow
2021년 4월 7일
Tony Castillo
2021년 7월 27일
Dear all,
I have a similar error message but in this case is because I just want to stack some values in a Bar plot, do you have any insights to overcome this?
Assigning to 2 elements using a simple assignment statement is not supported. Consider
using comma-separated list assignment.
Error in barconvariasVariables (line 20)
b2.BarWidth = 0.4;
energy_=linspace(1000, 3000, 12)';
cons_=linspace(900, 2300, 12)';
g_c= linspace(700, 2000, 12)';
HDW_c=linspace(100, 300, 12)';
Power_=linspace(1000, 3000, 12)';
Sp_ =linspace(10, 30, 12)';
EV_=linspace(500, 1900, 12)';
COF=3.7;
n=12;
U1=[energy_, (cons_ + g_c + HDW_c)*(COF-1)];
U2=[(Power_ + Sp_ + EV_), (cons_ + g_c + HDW_c)*COF];
b1= bar(U1,'stacked');
b1(1).BarWidth = 0.4;
hold on;
b2=bar(U2,'stacked');
b2.BarWidth = 0.4;
b2.XData = (1:n) - 0.5; % move bars left
xlabel('Months', 'FontWeight','bold')
ylabel('Consumption vs RES (kWp)', 'FontWeight','bold')
grid on
Stephen23
2021년 7월 27일
[b2.BarWidth] = deal(0.4);
카테고리
도움말 센터 및 File Exchange에서 Deploy to C++ Applications Using mwArray API (C++03)에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
