How do I access and edit a cell array using a double for indexes?
显示 更早的评论
Hi everyone,
working on some data, I came across a topic I avoided since starting with Matlab half a year ago. It's about indexing, accessing and editing data in a cell array. For example I got a 300000x1 cell array 'results' filled with 50 city names stored in a 50x1 cell named 'cities'. So each cell of 'results' contains one of the 50 names. What I want to do, is replacing the names in 'results' with their position/index in 'cities', in order to turn it into a double array and to save computing time for following tasks. I tried the following.
for k=1:length(cities)
cells = find(ismember(results,cities(k,1)));
results(cells) = k;
end;
Wich just produces the error Conversion to cell from double is not possible. I tried this because cells contains the indexes in 'results' of the just called city (cities(k,1)) And i thought this way I could also edit the values, which is obviously not possible.
My workaround would be the combination of 2 for loops, which is, regarding the length of the 'results' arrays, pretty slow.
for k=1:length(cities)
cells = find(ismember(results,cities(k,1)));
for n=1:length(cells)
results{cells(n,1),1} = num2str(k); %num2str because otherwise k-loop would not work for k>=2
end;
end;
% cellfun(@str2num, results(:,1)) in the end to convert the strings to num
But how do I get the first solution to work? How to I access the cell array correctly with a double as indexing? And is the first way really faster than the 'loop-Way'?
Many thanks in advance!
Best regards!
采纳的回答
更多回答(1 个)
results2 = cellfun(@(c) find(ismember(cities, c)), results);
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!