How to repeat value in Cell using MATLAB
34 次查看(过去 30 天)
显示 更早的评论
Hello Everyone, I hope you are doing well
I have two cell array one is Value and other is Counts. Each Value in cell has specific count,
I want to repeat the element using count.
for example Value=1 its Counts=15 Then the values repeat 15 times , now the new cell has 15 Values for each [1,2,3,4] and it applied on ALL cells.
How can i do that in Matlab
0 个评论
采纳的回答
dpb
2022-6-27
编辑:dpb
2022-6-27
fnRM=@(v,c)repmat(v,1,c);
for i=1:numel(Value)
C{i}=cell2mat(arrayfun(fnRM,Value{i},Counts{i},'UniformOutput',false).');
end
works if you replace the NaN in the Counts arrays with 0; you can't use a NaN in repmat.
You'll just have to define what is intended with the NaN Value elements -- are any NaN to show up in output or not.
ix=isfinite(Counts{i});
C{i}=cell2mat(arrayfun(fnRM,Value{i}(ix),Counts{i}(ix),'UniformOutput',false).');
inside the loop works to ignore the NaN entries as well without changing the data arrays.
4 个评论
dpb
2022-6-28
编辑:dpb
2022-6-28
Well, your original input cell arrays are row vectors...just transpose the output from cell2mat, of course...
>> for i=1:numel(Value),ix=isfinite(Counts{i});C{i}=cell2mat(arrayfun(fnRM,Value{i}(ix),Counts{i}(ix),'UniformOutput',false).').';end
>> C
C =
1×6 cell array
{60×1 double} {86×1 double} {98×1 double} {15×1 double} {12×1 double} {12×1 double}
>>
It's more bother to catenate vertically initially because they aren't all the same length.
更多回答(1 个)
Johan
2022-6-27
Hello, I don't know if there is a builtin matlab function to do what you want, this should work:
Value = {1,2,3}
Count = {2,1,5}
%Not sure if you want to repeat the same value or count from the value up
%to count
Final = cellfun(@(x,y) repmat(x,1,y),Value,Count,'UniformOutput',0)
Final = cellfun(@(x,y) x+cumsum(ones(y,1))-1,Value,Count,'UniformOutput',0);
Final{1}, Final{2}, Final{3}
best,
Johan
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!