How can I identify value of an array?
3 次查看(过去 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!