How can I identify value of an array?
조회 수: 2 (최근 30일)
이전 댓글 표시
Hi! I'm creating a code with Matlab but I've a problem.
I have an array, that is:
C = [2,1,0];
I've identified position of values, like:
C1 = C (1)
C2 = C (2)
C3 = C (3)
but I'd like to insert an input, that asks to user to insert the different values of array, so I can not know how many values will be in array.
In this case, how can I identify the position of single elements, given an input with a generic number of elements?
I thought to create a 'for cycle' but I have many problems!
Thank you
댓글 수: 7
Stephen23
2018년 5월 2일
편집: Stephen23
2018년 5월 7일
@sc: why do you need to do this? Using indexing is simple and very efficient. What you are trying to do is slow, complex, buggy, and hard to debug. Experienced MATLAB users use indexing: you can too.
EDIT: see also later question, where the OP asks about what they are actually trying to achieve:
채택된 답변
Jan
2018년 4월 30일
Maybe you want something like this:
C = [2,1,0];
index = find(C == 1);
Or
[match, index] = ismember([1,2], C);
추가 답변 (1개)
Guillaume
2018년 4월 30일
편집: Guillaume
2018년 4월 30일
Please, do read the discussion on the link in Dennis' comment. The code you've written is exactly why we say not to number variables and use eval. It's pointless complicated.
Before that,
b = 9;
num_int = numel(files)/b;
for k = 1 : num_int
Ck = [];
for n = 1:b
C_end = C(:,:,K+num_int*(n-1));
Ck = cat(3,Ck,C_end);
end
I'm not entirely sure what you're doing here since K is not defined. Assuming that there is a typo and K is k then all you're doing is deinterlacing data. In which case:
b = 9;
assert(mod(numel(files), b) == 0, 'Number of files must be a multiple of b'); %always a good idea to check your assumptions
num_int = numel(files) / b;
Ck = C(:, :, (1:num_int) + (0:b-1)' * num_int); %requires R2016b
%Ck = C(:, :, bsxfun(@plus, 1:num_int, (0:b-1)' * num_int)); %on earlier versions
This will be much faster than your double loop and your growing Ck array.
Then the whole numbered Cbxx, CBxx_new, etc. is completely pointless. If all you want to do is reorder things, then use indexing:
C_input = [1000,700,500,350,200,100,50,15,0];
order = [9 1 2 3 4 5 6 7 8 9];
new_cb = C_input(order);
C = Ck(:, :, order);
or something like that. Again, I'm really not clear on what you're trying to do. One thing for sure, you do not need numbered variables and eval.
댓글 수: 3
Guillaume
2018년 5월 2일
I'm afraid I don't really understand what exactly changes with user input and what you want to do with it. An array does not contain variables. Can you describe a bit better what's supposed to change and what calculation should be done as a result.
One thing for sure, even if the size of an array is not fixed, indexing is going to be the solution.
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!