Replace values in one column in multiple cells in array

조회 수: 5 (최근 30일)
mzaya
mzaya 2016년 2월 23일
댓글: Amos 2016년 2월 23일
I'm trying to replace the 5th column in each cell in a cell array with the 5th column of each cell from another cell array. I made the following function, which does this but also replaces the values in all other columns with 0. How do I do this without deleting all other values from the other columns. The function is:
function [X]=replace_cells(cell)
X={};
for i=1:length(cell)
X{i}(:,[5])=cell{i}(:,[5]);
end
  댓글 수: 4
Amos
Amos 2016년 2월 23일
편집: Amos 2016년 2월 23일
then I can't see why your code should not work ... if you post a full example (including test cell arrays), people can have a look at the issue
edit: wait, you shouldn't initialize X as empty cell array, but rather give it as an input to your function...
mzaya
mzaya 2016년 2월 23일
Yes that was the main issue, thanks! New code is as follows and it works:
function X=replace_cells(c,X)
for i=1:length(c)
X{i}(:,5)=c{i}(:,5);
end
end

댓글을 달려면 로그인하십시오.

채택된 답변

Amos
Amos 2016년 2월 23일
Maybe try:
function [X]=replace_cells(cell,X)
for i=1:length(cell)
X{i}(:,[5])=cell{i}(:,[5]);
end
  댓글 수: 2
Guillaume
Guillaume 2016년 2월 23일
편집: Guillaume 2016년 2월 23일
Please replace the variable name cell with something that is not a matlab function. While it does not cause any problem in this short function, it is still confusing to the casual reader.
For that matter, using meaningful names for all variables would be much better. How about:
function destination = replace_cell(destination, source, column)
assert(size(destination) == size(source));
for cidx = 1:numel(source)
destination{cix}(:, column) = source{cidx}(:, column);
end
end
Also note that I'm using numel instead of length. My version works regardless of the shape of source and destination (vector, 2D, 3D, ND) as long as they're the same size. The original code with length would utterly fail on 2D or ND cell arrays.
Amos
Amos 2016년 2월 23일
Indeed, this suggestion is much better Matlab code.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by