cell2mat in a for loop
5 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Hello,
I am trying to use the cell2mat in a for loop in order to convert my cell array in a double array. The code looks like the one below:
for j=1:length(j)
for ii=1:lentgh(A)
y = constants*A(ii) + constants*A(ii)*B(j) %my equation
end
pos{j,ii} = find(y >= 0, 1); %find the first position of y that crosses the zero
zero = cell2mat(pos); %convert the cell array into a normal array (double in this case since I am varying 2 parameters)
C_new = C(zero); %find the corresponding values at that position
end
The reason why I am using pos as a cell array is because by using a normal array, the code gives me error (because the values in the equation are too small, in fact the first cell of the array are empty) but I don't want my values to get overwritten. In the end, I should obtain a jxii matrix for zero (and for C_new as well).
How can I solve this problem?
10 Commenti
Alex Mcaulley
il 27 Feb 2019
I think you should use something like that. Anyway, if you provide examples for A,B,C and what you expect for Cnew it will be easier
A = [1,2,3,4];
B = [1,2,3,4,5];
constant1 = 5;
constant2 = 5;
y = (A'*(constant1*ones(size(B)) + constant2*B))';
C = ones(size(y));
Cnew = C(y >= 0);
Risposte (1)
Guillaume
il 28 Feb 2019
As I explained in point 2) of my comment, in the code you've posted, the ii loop does nothing useful and only the last step affects y. You still haven't explained properly what you're doing so it's difficult to give you a good solution to your problem. I also completely forgot to mention that with your given code,
pos{j, ii} = something;
is the same as
pos{j, length(A)} = something;
since the assignment is outside of the ii loop. And elements pos{j, 1:length(A)-1} will always be empty.
Instead, I'm just going to solve the immediate problem of "I logically get the error "Array indices must be positive integers or logical values." when computing C_new = C(zero)" as it's the best we can do.
%As pointed out, the loop code in the question makes absolutely no sense
%so making up some demo code. Adapt as required
A = 1:10;
B = 1:5;
x = linspace(0, 2*pi, 100);
C = x;
%algorithm
pos = nan(numel(A), numel(B)); %predeclare array
for col = 1:numel(B)
for row = 1:numel(A)
y = sin(x*A(row)) - cos(x*B(col)) - 2*mod(A(row)+B(col), 2); %some equation that will always be negative for some A and B
zerocross = find(y >= 0, 1);
if ~isempty(zerocross)
pos(row, col) = zerocross
end
end
end
%at this point we have pos, a matrix of indices with some NaN in it when there was no positive values in y
%we want a Cnew matrix which has C(pos) for the non NaN values:
Cnew = nan(size(pos));
Cnew(~isnan(pos)) = C(pos(~isnan(pos))); %only copy C values for which pos is non-nan.
0 Commenti
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!