How to use cell2mat in a for loop?
3 次查看(过去 30 天)
显示 更早的评论
I have a column of data imported from a text file.
allcomponents =
Columns 1 through 11
'M1' 'M2' 'M3' 'M4' 'M5' 'M6' 'M7' 'M8' 'VDD' 'V+' 'VSS'
Columns 12 through 14
'Ib' 'Cc' 'CL'
and I have tried cell2mat in for loop as:
1.
for i = 1:NoofComponents
b = cell2mat(Component(i))
end
which gives separate b values
2.
for i = 1:NoofComponents
b(i) = cell2mat(Component(i))
end
error: In an assignment A(:) = B, the number of elements in A and B must be the same.
3.
for i = 1:NoofComponents
b(i,:) = cell2mat(Component(i,:))
end
error: Subscripted assignment dimension mismatch.
How do I over come this issue?
Am I doing wrong?
I want result b as
M1
M2
M3
M4
M5
M6...
4 个评论
Stephen23
2018-6-12
"I want result b as..."
M1
M2
M3
M4
M5
M6...
Can you please clarify exactly what you want, because your example is not clear. Do you want to display those values in a list in the command window, or create one char array containing those values, or something else?
回答(1 个)
Walter Roberson
2018-6-12
allcomponents(:)
This would be the cell array {'M1'; 'M2'; 'M3'; 'M4' ... }
If you are wanting the N x 2 character array ['M1'; 'M2'; 'M3'; 'M4' ... ]
then
char(allcomponents(:))
if the entries are not all the same size, the shorter ones will be blank padded.
But I have to wonder if what you are asking for is to take the character vectors 'M1', 'M2', and so on, and to put the contents of variables with the corresponding name into a data structure, as if you had variables M1, M2, etc, and had entered
[M1; M2; M3; ...]
?? If so then we do not recommend doing that.
I wonder if you should be using readtable() to read in your data?
Or if perhaps what you should be doing is skipping the first line of your input (the one with the labels) and reading in the rest as numeric, and then using (:) to convert to a single long vector?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!