Writing a cell array to excel but skipping certain values

조회 수: 3 (최근 30일)
Magnus
Magnus 2012년 2월 20일
편집: Cedric 2013년 10월 22일
I am currently working on code that will write values from a x*1 cell array to an excel file. I need to write each 15th value to an excel file (this I have managed to do).
This is what I am using to write each 15th cell in the cell array: x_new=X(15:15:end); xlswrite('test.xlsx', X_new)
Now, what I need help with is to some code to this that will let me be able to skip certain values of this x*1 cell array. I want to write each 15th value, but I want to skip all 0 values. However, I cannot remove the 0 values before I write to excel. I need to write each 15th value to excel, but if it is ever 0 (if number cell number 15, 30 or 45 is zero) then that should be skipped and the next value (not zero) should be written instead, before it goes back to writing each 15th cell.
Is this clear? I do not have much experience with matlab, and I am using it to collect data for my master thesis.

답변 (1개)

Sarah Wait Zaranek
Sarah Wait Zaranek 2012년 2월 20일
I think it is clear what you want to do- I don't have MATLAB open, so forgive minor syntax issues.
1. Step one extract the every 15th points
x_new = X(15:15:end);
x_new = cell2mat(x_new); %changing into double array
x_idx = ((1:length(x_new))) * 15; % index in ref to x
2. Find if any zeros exist
ind = find(x_new==0);
3. Replace existing values with idx + 1 values
x_new(ind) = [X{x_idx(ind)+1}];
4. Write out x_new to excel
** Edited **
New version of code including check if x_new is a cell array
%%New version of the code
X = num2cell(rand(500,1));
X{15} = 0;
X{135} = 0;
X{300} = 0;
x_new = X(15:15:end);
% Make sure you are working with a cell array
if iscell(x_new)
x_new = X(15:15:end);
x_new = cell2mat(x_new); %changing into double array
x_idx = ((1:length(x_new))) * 15; % index in ref to x
ind = find(x_new==0);
x_new(ind) = [X{x_idx(ind)+1}];
else
disp('Your variable not a cell')
end
  댓글 수: 8
Sarah Wait Zaranek
Sarah Wait Zaranek 2012년 3월 8일
I assume that the value next to the zero is not a zero. If it is a zero, you need to do a check and advance one more.
Magnus
Magnus 2012년 3월 12일
I managed, with help, to solve my problem, thank you for your answer =)

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by