1

I am doing a project where I would like to vectorize (if possible), these lines of code in Matlab:

for j=1:length(image_feature(i,:))
    string1b=strcat(num2str(j),':',num2str(image_feature(i,j)));
    write_file1b=[write_file1b string1b ' '];
end

Basically, what I want to get is an output string in the following way:

1:Value1 2:Value2 3:Value3 ....

Note that ValueX is a number so a real example would be an output like this:

1:23.2 2:34.3 3:110.8 

Is this possible? I was thinking about doing something like creating another vector with values from 1 to j, and another j-long vector with only ":", and a num2str(image_feature(i,:)), and then hopefully there is a function f (like a vectorized strcat) that if I do:

f(num2str(1:j),colon_vector,num2str(image_feature(i,:))) 

will give me the output I mention above.

2 Answers 2

2

Im not sure I understood your question but perhaps this might help

val=[23.2 34.3 110.8]
output = [1:length(val); val]
sprintf('%i: %f ',output)

As output I get

1: 23.200000 2: 34.300000 3: 110.800000
Sign up to request clarification or add additional context in comments.

Comments

2

You can vectorize all your array operations to create an array or matrix of numbers very efficiently, but by the very nature of strings in MATLAB, you cannot vectorize the creation of your output string. Theoretically, if you have a fixed length string like in C++, you could concurrently write to different memory locations within the string, but that is not something that is supported by MATLAB. Even if it were, it looks like you have variable-length numbers, so even that would be difficult (unless you were to allocate a specific amount of space per number pair, leading to variable-length spaces between number pairs. It doesn't look like you want to do that, since your examples have exactly one space between all number pairs).

If you'd be interested in efficiently creating a vector, the answer provided by twerdster would accomplish that, but even in that code, the sprintf statement is not concurrent. His code does get rid of the for-loop, which improves efficiency, so I prefer his code to yours.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.